package app

import (
	"database/sql"
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"

	"gitee.com/tomatomeatman/golang-repository/bricks/model/dbinfo"
	"gitee.com/tomatomeatman/golang-repository/bricks/model/msgentity"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/integerutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/stringutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/timeutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/reflectutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/gorm"
	Log "github.com/cihub/seelog"
)

// we数据层接口定义,用于规范控制层结构体
type Dao interface {

	/**
	 * 新增
	 * @param entity 待保存实体
	 */
	Add(entity dbinfo.Entity) *msgentity.MsgEntity

	/**
	 * 通用新增数据方法
	 * @param entity 待保存实体
	 */
	AddCommon(entity dbinfo.Entity) *msgentity.MsgEntity

	/**
	 * 新增树节点
	 * @param entity 检查用数据结构
	 */
	AddNode(entity dbinfo.Entity) *msgentity.MsgEntity

	// 批量新增
	Adds(entitys []dbinfo.Entity) *msgentity.MsgEntity

	/**
	 * 修改状态
	 * @param entity 实体类
	 * @param id 编号
	 * @param iState 状态值
	 * @param iVersion 记录版本号
	 * @param sMemo 备注
	 * @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
	 * @return msgentity.MsgEntity 返回执行情况
	 */
	ChangeState(entity dbinfo.Entity, id interface{}, iState int, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity

	/**
	 * 修改步骤值(如果设置为单向则新值必须大于旧值)
	 * @param id 编号
	 * @param iSetp 步骤值
	 * @param iVersion 记录版本号
	 * @param sMemo 备注
	 * @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
	 * @param entity 实体类
	 * @return msgentity.MsgEntity 返回执行情况
	 */
	ChangeSetp(entity dbinfo.Entity, id interface{}, iSetp int, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity

	// 逻辑删除(非物理删除)
	DelSign(entity dbinfo.Entity, id interface{}, iVersion int, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	// 逻辑删除(非物理删除)
	DelSignByMap(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	// 删除
	Del(entity dbinfo.Entity, id interface{}, iVersion int, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	// 删除
	DelByMap(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 修改
	 * @param entity 对象类型
	 * @param id 记录编号值
	 * @param iVersion 记录版本号
	 * @param data 待更新的字段和值
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	Edit(entity dbinfo.Entity, id interface{}, iVersion int, data map[string]interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据主键查询数据
	 * @param entity 检查用数据结构
	 * @param id 主键
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	FindById(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据主键查询数据(返回结构体数据)
	 * @param entity 检查用数据结构
	 * @param id 主键
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	EntityById(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	EntityBySql(entityList interface{}, sql string, where map[string]interface{}) *msgentity.MsgEntity

	/**
	 * 查询所有数据
	 * @param entity 检查用数据结构
	 * @param where 查询条件
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	FindAll(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 查询指定时间内数据
	 * @param entity 检查用数据结构
	 * @param sDateSt 开始时间
	 * @param sDateEd 结束时间
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	FindByDate(entity dbinfo.Entity, sDateSt string, sDateEd string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 查询指定行数据
	 * @param entity 检查用数据结构
	 * @param id 记录编号
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	FindByRow(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 查询分页数据
	 * @param entity 检查用数据结构
	 * @param findByPageParam 分页参数
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅创建用户
	 * @return msgentity.MsgEntity
	 */
	FindByPage(entity dbinfo.Entity, findByPageParam dbinfo.FindByPageParam, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	// 取路径字段
	GetPath(sId, dbName, tableName string) string

	/**
	 * 取指定节点下的子节点编号
	 * @param tableInfo 表信息
	 * @param sPid 父节点
	 * @return
	 */
	NewChildId(tableInfo dbinfo.Entity, sPid string) *msgentity.MsgEntity

	/**
	 * 验证新增数据是否存在重复
	 * @param entity 数据实体
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	ValidEntityRepeatByAdd(entity dbinfo.Entity, currentUser string) *msgentity.MsgEntity

	/**
	 * 验证更新数据是否存在重复
	 * @param entity 数据实体
	 * @param id 主键
	 * @param data 数据
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	ValidEntityRepeatByEdit(entity dbinfo.Entity, id interface{}, data map[string]interface{}, currentUser string) *msgentity.MsgEntity

	/**
	 * 通用树型结构表添加数据时重复检查方法
	 * @param entity 数据实体
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	CommonCheckRepeatByAddAndTree(entity dbinfo.Entity, currentUser string) *msgentity.MsgEntity

	/**
	 * 通用树型结构表添加数据时重复检查方法
	 * @param entity 数据实体
	 * @param id 主键
	 * @param sName 展现名
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	CommonCheckRepeatByEditAndTree(entity dbinfo.Entity, id interface{}, sName interface{}, currentUser string) *msgentity.MsgEntity

	/**
	 * 通用添加数据时重复检查方法
	 * @param entity 数据实体
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	CommonCheckRepeatByAdd(entity dbinfo.Entity, currentUser string) *msgentity.MsgEntity

	/**
	 * 通用更新数据时重复检查方法
	 * @param entity 数据实体
	 * @param id 数据主键
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	CommonCheckRepeatByEdit(entity dbinfo.Entity, id interface{}, currentUser string) *msgentity.MsgEntity

	/**
	 * 读取树形结构数据
	 * @param entity 数据实体
	 * @param sGroupColumn 分组字段
	 * @param sGroupName 分组名称
	 * @param currentUser 当前用户
	 * @return msgentity.MsgEntity
	 */
	FindByTree(entity dbinfo.Entity, sGroupColumn, sGroupName string, currentUser string) *msgentity.MsgEntity

	/**
	 * 根据字段名取指定记录编号的数据库表中对应字段的值
	 * @param entity 实体类
	 * @param id 记录编号
	 * @param fieldNames 待取数据的字段名称集合
	 * @param currentUser 当前用户
	 * @Param onlyCreator 是否只取当前用户创建的数据
	 * @return msgentity.MsgEntity 返回内容data中存放的是Map
	 */
	GetValueByFieldName(entity dbinfo.Entity, id interface{}, fieldNames []string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据字段名取指定记录编号的数据库表中对应字段的值
	 * @param entity 实体类
	 * @param id 记录编号
	 * @param fieldName 待取数据的字段名称集合
	 * @param currentUser 当前用户
	 * @Param onlyCreator 是否只取当前用户创建的数据
	 * @return msgentity.MsgEntity 返回内容data中存放的是Map
	 */
	GetValueByField(entity dbinfo.Entity, id interface{}, fieldName, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据字段名取指定条件的数据库表中对应字段的值
	 * @param entity 实体类
	 * @param whereInfo 条件
	 * @param fieldName 待取数据的字段名称集合
	 * @param currentUser 当前用户
	 * @Param onlyCreator 是否只取当前用户创建的数据
	 * @return msgentity.MsgEntity 返回内容data中存放的是Map
	 */
	GetValueByWhere(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 取记录对应的版本号
	 * @param entity 实体类
	 * @param idName 编号
	 * @return
	 */
	GetiVersion(entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity

	/**
	 * 取记录对应的状态值
	 * @param entity 实体类
	 * @param id 编号
	 * @return
	 */
	GetiState(entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity

	/**
	 * 根据关键值取对象集合
	 * @Param entity 实体类
	 * @Param where 存放查询条件
	 * @Param currentUser 当前用户
	 * @Param onlyCreator 是否只取当前用户创建的数据
	 * @return msgentity.MsgEntity
	 */
	FindByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据关键值取对象集合中的第一个
	 * @Param entity 实体类
	 * @Param where 存放查询条件
	 * @Param currentUser 当前用户
	 * @param onlyCreator 是否只取当前用户创建的数据
	 * @param fields 指定要查询的字段集合
	 * @return msgentity.MsgEntity
	 */
	FindOneByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool, fields ...string) *msgentity.MsgEntity

	/**
	 * 根据关键值取对象集合中的符合条件的第一条记录的指定字段
	 * @Param entity 实体类
	 * @Param where 存放查询条件
	 * @param fieldName 指定要查询的字段
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅查询创建者
	 * @return msgentity.MsgEntity
	 */
	FindValueByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据关键值取对象集合中的符合条件的第一条记录的指定字段
	 * @Param entity 实体类
	 * @Param where 存放查询条件
	 * @param fieldMap 指定要查询的字段集合(原字段, 别名)
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅查询创建者
	 * @return msgentity.MsgEntity
	 */
	FindByFields(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldMap map[string]string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据关键值查数量
	 * @Param entity 实体类
	 * @Param where 存放查询条件
	 * @param currentUser 当前用户
	 * @param onlyCreator 仅查询创建者
	 * @return msgentity.MsgEntity
	 */
	FindCountByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 以事务方式执行多个sql
	 * 注意:Mapper必须存在才能执行
	 * @param sqls [sql, params]
	 * @return msgentity.MsgEntity 一个执行失败则回滚
	 */
	TransactionSql(sqls map[string]map[string]interface{}) *msgentity.MsgEntity

	/**
	 * 根据字段名取分组数据
	 * @param entity 实体类
	 * @param sCreator 指定用户
	 * @param fields 字段名与别名对象
	 * @param currentUser 当前用户
	 * @param onlyCreator 用户查询限制(仅创建者可见)
	 * @return
	 */
	GroupByField(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据字段名取分组数据,并返回数量
	 * @param entity 实体类
	 * @param sCreator 指定用户
	 * @param fields 字段名与别名对象
	 * @param currentUser 当前用户
	 * @param onlyCreator 用户查询限制(仅创建者可见)
	 * @return
	 */
	GroupByFieldAndCount(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 根据字段名取分组数据
	 * @param entity 实体类
	 * @param sCreator 指定用户
	 * @param fields 字段名与别名对象
	 * @param currentUser 当前用户
	 * @param onlyCreator 用户查询限制(仅创建者可见)
	 * @param isGroupCount 添加分组后是否添加'数量列'
	 * @return
	 */
	GroupByFieldBase(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator, isGroupCount bool) *msgentity.MsgEntity

	/**
	 * 取表中指定字段的最大值
	 * @param entity 实体类
	 * @param sCreator 指定用户
	 * @param field 字段名
	 * @param where 查询条件
	 * @param currentUser 当前用户
	 * @param onlyCreator 用户查询限制(仅创建者可见)
	 * @return msgentity.MsgEntity
	 */
	MaxByField(entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 取表中指定字段的最小值
	 * @param entity 实体类
	 * @param sCreator 指定用户
	 * @param field 字段名
	 * @param where 查询条件
	 * @param currentUser 当前用户
	 * @param onlyCreator 用户查询限制(仅创建者可见)
	 * @param whereStr 查询条件字符串
	 * @return
	 */
	MinByField(entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 检查关键值记录是否存在(返回1:存在;0:不存在)
	 * @param entity 实体类
	 * @param id 记录编号
	 * @return msgentity.MsgEntity
	 */
	HasById(entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity

	/**
	 * 检查关键值记录是否存在(返回1:存在;0:不存在)
	 * @param entity 实体类
	 * @Param keyName 字段名
	 * @Param keyValue 字段值
	 * @return msgentity.MsgEntity
	 */
	HasByKey(entity dbinfo.Entity, keyName string, keyValue interface{}) *msgentity.MsgEntity

	/**
	 * 执行SQL脚本获取单行单列数据
	 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
	 * @param sql 待执行的SQL脚本
	 * @param where 存放查询条件
	 * @return msgentity.MsgEntity
	 */
	DoSql(sql string, where ...interface{}) *msgentity.MsgEntity

	/**
	 * 执行SQL脚本获取单行单列数据
	 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
	 * @param sql 待执行的SQL脚本
	 * @param where 存放查询条件
	 * @return msgentity.MsgEntity
	 */
	ExecSql(sql string, where ...interface{}) *msgentity.MsgEntity

	/**
	 * 执行SQL脚本获取单行单列数据
	 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
	 * @param sql 待执行的SQL脚本
	 * @param where 存放查询条件
	 * @return msgentity.MsgEntity
	 */
	GetValue(sql string, where ...interface{}) *msgentity.MsgEntity

	/**
	 * 执行SQL脚本获取一行数据(多列)
	 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录
	 * @param sql 待执行的SQL脚本
	 * @param where 存放查询条件
	 * @return msgentity.MsgEntity
	 */
	GetRow(sql string, where ...interface{}) *msgentity.MsgEntity

	/**
	 * 执行SQL脚本获取多行数据(多列)
	 * 注意:库名必须用${}进行包装,此脚本可返回多条记录
	 * @param sql SQL脚本
	 * @param where 存放查询条件
	 * @return msgentity.MsgEntity
	 */
	GetRows(sql string, where ...interface{}) *msgentity.MsgEntity

	/**
	 * 根据关键值翻转值(限布尔值类型,1转2,2转1)
	 * @Param entity 实体类
	 * @Param whereInfo 存放查询条件
	 * @Param reversalColumn 翻转的字段名
	 * @Param currentUser 当前用户
	 * @Param onlyCreator 是否只翻转创建人创建的数据
	 * @return msgentity.MsgEntity
	 */
	ReversalByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, reversalColumn, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	* 根据条件仅查询指定字段名数据
	* @param entity 实体类
	* @param whereInfo
	* @param fieldNames 待取数据的字段名称集合
	* @Param currentUser 当前用户
	* @Param onlyCreator 是否只翻转创建人创建的数据
	* @return msgentity.MsgEntity 返回内容data中存放的是Map
	 */
	FindField(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldNames []string, currentUser string, onlyCreator bool) *msgentity.MsgEntity

	/**
	 * 设置父对象
	 * @param owner 父对象
	 */
	SetOwner(owner Dao)

	// 对gorm.First操作进行封装
	First(entity dbinfo.Entity, conds ...interface{}) (dbinfo.Entity, error)

	// 对gorm.Create操作进行封装
	Create(entity dbinfo.Entity) (dbinfo.Entity, error)

	// 对gorm.Save操作进行封装,
	// 警告:Save是一个组合函数。 如果保存值不包含主键，它将执行 Create，否则它将执行 Update (包含所有字段)。
	Save(entity dbinfo.Entity) (dbinfo.Entity, error)

	// 对gorm.Delete操作进行封装
	Delete(entity dbinfo.Entity, conds ...interface{}) (int, error)
}

var CommonDao = &DaoBaseFunc{}

type DaoBaseFunc struct {
	owner Dao //指定上级
}

/**
 * 设置父对象
 * @param owner
 */
func (dao *DaoBaseFunc) SetOwner(owner Dao) {
	dao.owner = owner
}

/**
 * 新增
 * @param entity 待保存实体
 */
func (dao DaoBaseFunc) Add(entity dbinfo.Entity) *msgentity.MsgEntity {
	if dbinfo.EntityHasPid(entity) {
		return dao.AddNode(entity)
	}

	return dao.AddCommon(entity)
}

/**
 * 通用新增数据方法
 * @param entity 待保存实体
 */
func (dao DaoBaseFunc) AddCommon(entity dbinfo.Entity) *msgentity.MsgEntity {
	dbResult := gorm.GetDB().Table(entity.TableName()).Create(entity)
	if dbResult.Error != nil {
		Log.Error("新增发生异常:", dbResult.Error)
		return msgentity.Err(8041, "新增发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(8042, "新增失败,影响数为0")
	}

	return msgentity.Success(entity, "新增成功")
}

/**
 * 新增树节点
 * @param entity 检查用数据结构
 */
func (dao DaoBaseFunc) AddNode(entity dbinfo.Entity) *msgentity.MsgEntity {
	// var dataEntity interface{}
	// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
	// if typeOf.Kind() == reflect.Ptr { //是否指针类型
	// 	dataEntity = entity
	// } else if "reflect.Value" == typeOf.String() {
	// 	dataEntity = entity.(reflect.Value).Interface()
	// } else {
	// 	dataEntity = reflect.ValueOf(entity)
	// }

	var build strings.Builder
	build.WriteString("INSERT INTO ")
	build.WriteString(entity.TableName())
	build.WriteString(" (@@@@@") //要替换'@@@@,'

	//未完
	// columns := dbinfo.TableInfo{}.GetColumnNames(entity)
	// for _, v := range columns {
	// 	if "/sPath/"
	// 	build.WriteString(v)

	// 	"CONCAT(IFNULL((select a.sPath from ${BricksBaseSystem}Department a where a.sId=IFNULL(#{sPid}, '00') ), '/00/'), #{sId}, '/') as sPath,"
	// }

	build.WriteString(" )")

	// params = append(params, sql.Named("iState", iState))

	// sMemo = strings.TrimSpace(sMemo)
	// if sMemo != "" {
	// 	build.WriteString(" ,sMemo=@sMemo")
	// 	params = append(params, sql.Named("sMemo", sMemo))
	// }

	// if 0 != iVersion {
	// 	build.WriteString(" ,iVersion=iVersion+1")
	// }

	dbResult := gorm.GetDB().Table(entity.TableName()).Create(entity)
	if dbResult.Error != nil {
		Log.Error("新增发生异常:", dbResult.Error)
		return msgentity.Err(8041, "新增发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(8042, "新增失败,影响数为0")
	}

	return msgentity.Success(entity, "新增成功")
}

// 批量新增
func (dao DaoBaseFunc) Adds(entitys []dbinfo.Entity) *msgentity.MsgEntity {
	if len(entitys) < 1 {
		return msgentity.Err(8041, "待批量新增的数据为空")
	}

	// dbResult := gorm.GetDB().Table(detail.OrdersDetailBase{}.TableName()).CreateInBatches(&entitys, 100)
	// if dbResult.Error != nil {
	// 	Log.Error("新增订单详情异常:", dbResult.Error)
	// 	return msgentity.Err(8002, "订单详情创建失败")
	// }

	//下面是事务方式批量添加
	var me *msgentity.MsgEntity
	gorm.GetDB().Transaction(func(tx gorm.GormDB) error {
		for _, entity := range entitys {
			// var dataEntity interface{}
			// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
			// if typeOf.Kind() == reflect.Ptr { //是否指针类型
			// 	dataEntity = entity
			// } else if "reflect.Value" == typeOf.String() {
			// 	dataEntity = entity.(reflect.Value).Interface()
			// } else {
			// 	dataEntity = reflect.ValueOf(entity)
			// }

			if err := tx.Table(entity.TableName()).Create(entity).Error; err != nil {
				Log.Error("批量新增发生异常:", err)
				me = msgentity.Err(8041, "批量新增发生异常:", err)
				return err
			}
		}

		me = msgentity.Success(entitys, "批量新增成功")
		return nil
	})

	return me
}

/**
 * 修改状态
 * @param entity 实体类
 * @param id 编号
 * @param iState 状态值
 * @param iVersion 记录版本号
 * @param sMemo 备注
 * @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
 * @return msgentity.MsgEntity 返回执行情况
 */
func (dao DaoBaseFunc) ChangeState(entity dbinfo.Entity, id interface{}, iState, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity {
	if fmt.Sprintf("%v", id) == "" {
		return msgentity.Err(7001, "记录编号参数为空！")
	}

	params := []interface{}{}
	params = append(params, sql.Named(dbinfo.EntityKeyName(entity)+"Where", id))

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(entity.TableName())
	build.WriteString(" SET ")
	build.WriteString(dbinfo.TableStateName)
	build.WriteString("=@")
	build.WriteString(dbinfo.TableStateName)
	params = append(params, sql.Named(dbinfo.TableStateName, iState))

	sMemo = strings.TrimSpace(sMemo)
	if sMemo != "" {
		build.WriteString(" ,")
		build.WriteString(dbinfo.TablesMemo)
		build.WriteString("=@")
		build.WriteString(dbinfo.TablesMemo)
		params = append(params, sql.Named(dbinfo.TablesMemo, sMemo))
	}

	if iVersion != 0 {
		build.WriteString(" ,")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString("= 1 + ")
		build.WriteString(dbinfo.TableVersionName)
	}

	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("Where")
	if iVersion != 0 {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString("=@iVersionWhere")
		params = append(params, sql.Named("iVersionWhere", iVersion))
	}

	if unidirectional {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableStateName)
		build.WriteString(" < @iStateWhere")
		params = append(params, sql.Named("iStateWhere", iState))
	}

	dbResult := gorm.Exec(build.String(), params)
	if dbResult.Error != nil {
		Log.Error("更新状态值发生异常:", dbResult.Error)
		return msgentity.Err(7005, "更新状态值发生异常:", dbResult.Error)
	}

	if 0 < dbResult.RowsAffected {
		return msgentity.Success(7999, "更新状态值成功！")
	}

	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(", ")
	build.WriteString(dbinfo.TableStateName)

	if iVersion != 0 {
		build.WriteString(", ")
		build.WriteString(dbinfo.TableVersionName)
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	var iStateOld, iVersionOld int
	row := gorm.Raw(build.String(), sql.Named(dbinfo.EntityKeyName(entity), id)).Row()
	row.Scan(&iStateOld, &iVersionOld)

	if iStateOld == 0 {
		return msgentity.Err(7001, "没有找到对应数据！")
	}

	if (iVersion != 0) && (iVersion != iVersionOld) {
		return msgentity.Err(7002, "更新状态值失败，系统中的数据可能已经被更新！")
	}

	if (iState >= 0) && (iState < iStateOld) {
		return msgentity.Err(7003, "更新状态值失败，状态禁止逆操作！")
	}

	Log.Error("更新状态值未能得到预期影响值(预期1):", dbResult.RowsAffected)
	return msgentity.Err(7004, "更新状态值未能得到预期影响值(预期1)", dbResult.RowsAffected)
}

/**
 * 修改步骤值(如果设置为单向则新值必须大于旧值)
 * @param id 编号
 * @param iSetp 步骤值
 * @param iVersion 记录版本号
 * @param sMemo 备注
 * @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
 * @param entity 实体类
 * @return msgentity.MsgEntity 返回执行情况
 */
func (dao DaoBaseFunc) ChangeSetp(entity dbinfo.Entity, id interface{}, iSetp, iVersion int, sMemo string, unidirectional bool) *msgentity.MsgEntity {
	if fmt.Sprintf("%v", id) == "" {
		return msgentity.Err(7001, "记录编号参数为空！")
	}

	params := []interface{}{}
	params = append(params, sql.Named(dbinfo.EntityKeyName(entity)+"Where", id))

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(entity.TableName())
	build.WriteString(" SET iSetp=@iSetp")
	params = append(params, sql.Named("iSetp", iSetp))

	sMemo = strings.TrimSpace(sMemo)
	if sMemo != "" {
		build.WriteString(" ,")
		build.WriteString(dbinfo.TablesMemo)
		build.WriteString("=@")
		build.WriteString(dbinfo.TablesMemo)
		params = append(params, sql.Named(dbinfo.TablesMemo, sMemo))
	}

	if iVersion != 0 {
		build.WriteString(" ,")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString(" = 1 + ")
		build.WriteString(dbinfo.TableVersionName)
	}

	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("Where")
	if iVersion != 0 {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString(" =@iVersionWhere")
		params = append(params, sql.Named("iVersionWhere", iVersion))
	}

	if unidirectional {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableSetpName)
		build.WriteString(" < @iSetpWhere")
		params = append(params, sql.Named("iSetpWhere", iSetp))
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	dbResult := gorm.Exec(build.String(), params)
	if dbResult.Error != nil {
		Log.Error("更新步骤值发生异常:", dbResult.Error)
		return msgentity.Err(7005, "更新步骤值发生异常:", dbResult.Error)
	}

	if 0 < dbResult.RowsAffected {
		return msgentity.Success(7999, "更新步骤值成功！")
	}

	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(", ")
	build.WriteString(dbinfo.TableSetpName)

	if iVersion != 0 {
		build.WriteString(", ")
		build.WriteString(dbinfo.TableVersionName)
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	var iSetpOld, iVersionOld int
	row := gorm.Raw(build.String(), sql.Named(dbinfo.EntityKeyName(entity), id)).Row()
	row.Scan(&iSetpOld, &iVersionOld)

	if iSetpOld == 0 {
		return msgentity.Err(7001, "没有找到对应数据！")
	}

	if (iVersion != 0) && (iVersion != iVersionOld) {
		return msgentity.Err(7002, "更新步骤值失败，系统中的数据可能已经被更新！")
	}

	if (iSetp >= 0) && (iSetp < iSetpOld) {
		return msgentity.Err(7003, "更新步骤值失败，状态禁止逆操作！")
	}

	Log.Error("更新步骤值未能得到预期影响值(预期1):", dbResult.RowsAffected)
	return msgentity.Err(7004, "更新步骤值未能得到预期影响值(预期1)", dbResult.RowsAffected)
}

// 逻辑删除(非物理删除)
func (dao DaoBaseFunc) DelSign(entity dbinfo.Entity, id interface{}, iVersion int, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if id == nil {
		return msgentity.Err(7001, "记录编号为空")
	}

	if !dbinfo.EntityHasDelSign(entity) { //有逻辑删除字段标识才能进行逻辑删除
		return msgentity.Err(1007, "没有逻辑删除字段,试图逻辑删除失败")
	}

	if dbinfo.EntityHasVersion(entity) && (iVersion < 1) && (iVersion != integerutil.MaxInt()) {
		return msgentity.Err(7002, "记录版本号不正确")
	}

	where := map[string]interface{}{}
	where[dbinfo.EntityKeyName(entity)] = id

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(entity.TableName())
	build.WriteString(" SET ")
	build.WriteString(dbinfo.TableDelSignName)
	build.WriteString(" = 1 WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasVersion(entity) && (iVersion != integerutil.MaxInt()) {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString("=@")
		build.WriteString(dbinfo.TableVersionName)
		where[dbinfo.TableVersionName] = iVersion
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("逻辑删除发生异常:", dbResult.Error)
		return msgentity.Err(1002, "逻辑删除发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected > 0 {
		return msgentity.Success(1999, "(逻辑)删除成功")
	}

	//--影响数为0,需要进一步判断--//
	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.TableDelSignName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = ? ")

	var iCount int
	gorm.Raw(build.String(), id).Scan(&iCount)
	if iCount == 0 {
		return msgentity.Success(1999, "没有发现此数据")
	}

	if !dbinfo.EntityHasVersion(entity) {
		return msgentity.Err(1003, "删除失败,数据还存在")
	}

	var oldVersion int
	var iDelSign int
	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.TableVersionName)
	build.WriteString(", ")
	build.WriteString(dbinfo.TableDelSignName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = ?")
	gorm.Raw(build.String(), id).Row().Scan(&oldVersion, &iDelSign)

	if iDelSign == 1 {
		return msgentity.Err(1004, "数据已经被(逻辑)删除")
	}

	if oldVersion == iVersion {
		return msgentity.Err(1005, "删除失败,数据还存在")
	}

	return msgentity.Err(1006, "(逻辑)删除失败,提供的版本号不正确,可能数据已经被改变")
}

// 逻辑删除(非物理删除)
func (dao DaoBaseFunc) DelSignByMap(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if !dbinfo.EntityHasDelSign(entity) { //有逻辑删除字段标识才能进行逻辑删除
		return msgentity.Err(1007, "没有逻辑删除字段,试图逻辑删除失败")
	}

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(entity.TableName())
	build.WriteString(" SET ")
	build.WriteString(dbinfo.TableDelSignName)
	build.WriteString(" = 1 WHERE 1=1")

	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("逻辑删除发生异常:", dbResult.Error)
		return msgentity.Err(1002, "逻辑删除发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected > 0 {
		return msgentity.Success(1999, "(逻辑)删除成功")
	}

	return msgentity.Err(1003, "(逻辑)删除失败")
}

// 删除
func (dao DaoBaseFunc) Del(entity dbinfo.Entity, id interface{}, iVersion int, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if id == nil {
		return msgentity.Err(7001, "记录编号为空")
	}

	if dbinfo.EntityHasVersion(entity) && (iVersion < 1) && (iVersion != integerutil.MaxInt()) {
		return msgentity.Err(7002, "记录版本号不正确")
	}

	where := map[string]interface{}{}
	where[dbinfo.EntityKeyName(entity)] = id

	var build strings.Builder
	build.WriteString("DELETE FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasVersion(entity) && (iVersion != integerutil.MaxInt()) {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString("=@")
		build.WriteString(dbinfo.TableVersionName)
		where[dbinfo.TableVersionName] = iVersion
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("删除发生异常:", dbResult.Error)
		return msgentity.Err(1002, "删除发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected > 0 {
		return msgentity.Success(1999, "删除成功")
	}

	//--影响数为0,需要进一步判断--//
	build.Reset()
	build.WriteString("SELECT 1 FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = ?")

	var iCount int
	gorm.Raw(build.String(), id).Scan(&iCount)
	if iCount == 0 {
		return msgentity.Success(1999, "没有发现此数据")
	}

	if !dbinfo.EntityHasVersion(entity) {
		return msgentity.Err(1003, "删除失败,数据还存在")
	}

	var oldVersion int
	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.TableVersionName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = ?")
	gorm.Raw(build.String(), id).Scan(&oldVersion)

	if oldVersion == iVersion {
		return msgentity.Err(1004, "删除失败,数据还存在")
	}

	return msgentity.Err(1005, "删除失败,提供的版本号不正确,可能数据已经被改变")
}

// 删除
func (dao DaoBaseFunc) DelByMap(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if entity == nil {
		return msgentity.Err(7001, "结构体参数为nil")
	}

	var build strings.Builder
	build.WriteString("DELETE FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("删除发生异常:", dbResult.Error)
		return msgentity.Err(1002, "删除发生异常:", dbResult.Error)
	}

	return msgentity.Success(1999, "删除成功")
}

/**
 * 修改
 * @param entity 对象类型
 * @param id 记录编号值
 * @param iVersion 记录版本号
 * @param data 待更新的字段和值
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) Edit(entity dbinfo.Entity, id interface{}, iVersion int, data map[string]interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if fmt.Sprintf("%v", id) == "" {
		return msgentity.Err(7001, "记录编号参数为空！")
	}

	params := []interface{}{} //[]sql.NamedArg{}
	params = append(params, sql.Named(dbinfo.EntityKeyName(entity), id))

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(entity.TableName())
	build.WriteString(" SET @@")

	for key, value := range data {
		build.WriteString(", ")
		build.WriteString(key)

		build.WriteString("=@")
		build.WriteString(key)
		params = append(params, sql.Named(key, value))
	}

	if dbinfo.EntityHasVersion(entity) {
		build.WriteString(", ")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString("= 1 + ")
		build.WriteString(dbinfo.TableVersionName)
	}

	if dbinfo.EntityHasModifieder(entity) {
		build.WriteString(",")
		build.WriteString(dbinfo.TableModifiederName)
		build.WriteString("=@")
		build.WriteString(dbinfo.TableModifiederName)
		params = append(params, sql.Named(dbinfo.TableModifiederName, currentUser))
	}

	if dbinfo.EntityHasModifiedDate(entity) {
		build.WriteString(", ")
		build.WriteString(dbinfo.TableModifiedDateName)
		build.WriteString("=NOW()")
	}

	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))

	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if (iVersion != 0) && dbinfo.EntityHasVersion(entity) {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableVersionName)
		build.WriteString("=@sCreator")
		params = append(params, sql.Named(dbinfo.TableCreatorName, iVersion))
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		params = append(params, sql.Named(dbinfo.TableCreatorName, currentUser))
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	txt := strings.Replace(build.String(), " @@, ", " ", -1)
	dbResult := gorm.Exec(txt, params)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return msgentity.Err(7005, "更新数据发生异常:", dbResult.Error)
	}

	if 0 < dbResult.RowsAffected {
		return msgentity.Success(7999, "更新数据成功！")
	}

	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasVersion(entity) {
		build.WriteString(", ")
		build.WriteString(dbinfo.TableVersionName)
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	var vId, iVersionOld int
	row := gorm.Raw(build.String(), sql.Named(dbinfo.EntityKeyName(entity), id)).Row()
	row.Scan(&vId, &iVersionOld)

	if (fmt.Sprintf("%v", vId) == "") || (fmt.Sprintf("%v", vId) == "<nil>") {
		return msgentity.Err(7001, "没有找到对应数据！")
	}

	if dbinfo.EntityHasVersion(entity) && (iVersion != iVersionOld) {
		return msgentity.Err(7002, "更新数据失败，系统中的数据可能已经被更新！")
	}

	Log.Error("更新数据未能得到预期影响值(预期1):", dbResult.RowsAffected)
	return msgentity.Err(7004, "更新数据未能得到预期影响值(预期1)", dbResult.RowsAffected)
}

/**
 * 根据主键查询数据
 * @param entity 检查用数据结构
 * @param id 主键
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindById(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if id == nil {
		return msgentity.Err(7001, "记录编号为空")
	}

	where := map[string]interface{}{"id": id}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("=@id")

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	rows, err := gorm.Raw(build.String(), where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7003, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7005, "查询成功,但没有数据")
	}

	return msgentity.Success(res[0], "查询成功")
}

/**
 * 根据主键查询数据(返回结构体数据)
 * @param entity 检查用数据结构
 * @param id 主键
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) EntityById(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if id == nil {
		return msgentity.Err(7001, "记录编号为空")
	}

	where := map[string]interface{}{"id": id}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("=@id")

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	dbResult := gorm.Raw(build.String(), where).Scan(entity)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(7002, "查询发生异常")
	}

	if dbResult.RowsAffected != 1 {
		return msgentity.Err(7003, "查询数据不符合")
	}

	return msgentity.Success(entity, "查询成功")
}

func (dao DaoBaseFunc) EntityBySql(entityList interface{}, sql string, where map[string]interface{}) *msgentity.MsgEntity {
	sql = strings.TrimSpace(sql)
	if sql == "" {
		return msgentity.Err(1001, "待执行语句为空")
	}

	if entityList == nil {
		return msgentity.Err(1002, "结构体为空")
	}

	result, err := gorm.Query(sql, entityList, where)
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(1003, "查询发生异常:", err)
	}

	return msgentity.Success(result, "查询成功")
}

/**
 * 查询所有数据
 * @param entity 检查用数据结构
 * @param where 查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindAll(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(entity.TableName())

	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留
	where := map[string]interface{}{}
	if len(whereInfo) > 0 {
		build.WriteString(" WHERE 1=1")
		for _, value := range whereInfo {
			condition := value.Condition
			if condition == "" {
				condition = "="
			}

			build.WriteString(" AND ")
			build.WriteString(value.Name)
			build.WriteString(" ")
			build.WriteString(condition)

			if value.ValueName != "" {
				build.WriteString(" ")
				build.WriteString(value.ValueName)
				continue
			}

			build.WriteString(" @")
			build.WriteString(value.Name)
			where[value.Name] = value.Value
		}
	}

	if onlyCreator && (currentUser != "") {
		where[dbinfo.TableCreatorName] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), "1=1 AND ", "", -1)

	rows, err := gorm.Raw(text, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(1005, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return msgentity.Err(1006, "查询后数据转换发生异常")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 查询指定时间内数据
 * @param entity 检查用数据结构
 * @param sDateSt 开始时间
 * @param sDateEd 结束时间
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindByDate(entity dbinfo.Entity, sDateSt string, sDateEd string, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	var dDateSt time.Time
	if sDateSt == "" {
		d, _ := time.ParseDuration("-168h") //7天前
		dDateSt = time.Now().Add(d)
	} else {
		temp, err := time.ParseInLocation("2006-01-02 15:04:05", sDateSt, time.Local)
		if err != nil {
			return msgentity.Err(7001, "'开始时间'格式不符合要求,推荐使用格式:'YYYY-MM-DD HH:mm:ss'")
		}

		dDateSt = temp
	}

	var dDateEd time.Time
	if sDateEd == "" {
		dDateEd = time.Now()
	} else {
		temp, err := time.ParseInLocation("2006-01-02 15:04:05", sDateSt, time.Local)
		if err != nil {
			return msgentity.Err(7002, "'结束时间'格式不符合要求,推荐使用格式:'YYYY-MM-DD HH:mm:ss'")
		}

		dDateEd = temp
	}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.TableCreateDateName)
	build.WriteString(" BETWEEN @dDateSt AND @dDateEd")

	where := map[string]interface{}{
		"dDateSt": dDateSt,
		"dDateEd": dDateEd,
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	rows, err := gorm.Raw(build.String(), where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return msgentity.Err(7004, "查询后数据转换发生异常")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 查询指定行数据
 * @param entity 检查用数据结构
 * @param id 记录编号
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindByRow(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	if id == nil {
		return msgentity.Err(7001, "记录编号为空")
	}

	sId := fmt.Sprintf("%v", id)
	if sId == "" {
		return msgentity.Err(7002, "记录编号为空")
	}

	// var s reflect.Type
	// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
	// if typeOf.Kind() == reflect.Ptr { //是否指针类型
	// 	s = reflect.TypeOf(entity).Elem() //通过反射获取type定义
	// } else {
	// 	s = typeOf //通过反射获取type定义
	// }

	var appendFieldSql strings.Builder
	var dictionarySql strings.Builder
	var oTherJoin = map[string]string{}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.SimpleTableName(entity))
	build.WriteString(".*,")

	dataInfoList := dbinfo.AllDataInfo(entity)
	for _, dataInfo := range dataInfoList {
		f, d := dao.GetFindByPageSelectSqlByField(dataInfo, dbinfo.SimpleTableName(entity), dataInfo.GsName, oTherJoin)
		if f != "" {
			appendFieldSql.WriteString(f)
		}

		if d != "" {
			dictionarySql.WriteString(d)
		}
	}

	build.WriteString(appendFieldSql.String())
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" AS ")
	build.WriteString(dbinfo.SimpleTableName(entity))

	if dictionarySql.String() != "" {
		build.WriteString(dictionarySql.String())
	}

	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" =@")
	build.WriteString(dbinfo.EntityKeyName(entity))

	where := map[string]interface{}{dbinfo.EntityKeyName(entity): id}
	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), ", FROM ", " FROM ", -1)

	rows, err := gorm.Raw(text, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(1005, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return msgentity.Err(1006, "查询后数据转换发生异常")
	}

	if len(res) < 1 {
		return msgentity.Success(res, "查询成功,但没有数据")
	}

	return msgentity.Success(res[0], "查询成功")
}

/**
 * 查询分页数据
 * @param entity 检查用数据结构
 * @param findByPageParam 分页参数
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindByPage(entity dbinfo.Entity, findByPageParam dbinfo.FindByPageParam, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	findByPageCountSql, findByPageSql, params := dao.GetFindByPageSelectSql(currentUser, entity, findByPageParam, onlyCreator)

	var iCount int
	dbResult := gorm.Raw(findByPageCountSql, params).Find(&iCount)

	// var dbResult *ggorm.DB
	// if len(params) < 1 {
	// 	dbResult = gorm.Raw(findByPageCountSql).Find(&iCount)
	// } else {
	// 	dbResult = gorm.Raw(findByPageCountSql, params).Find(&iCount)
	// }

	if dbResult.Error != nil {
		Log.Error("查询分页数量发生异常:", dbResult.Error)
		return msgentity.Err(7001, "查询分页数量发生异常:", dbResult.Error)
	}

	if iCount < 1 {
		res := make([]map[string]interface{}, 0)
		page := findByPageParam.Gpage
		page.GiCountRow = 0
		page.SetRecord(res)

		return msgentity.Success(page, "查询分页数量成功但没有数据")
	}

	rows, err := gorm.Raw(findByPageSql, params).Rows()
	if err != nil {
		Log.Error("查询分页数量发生异常:", err)
		return msgentity.Err(7002, "查询分页数量发生异常")
	}
	defer rows.Close()

	page := findByPageParam.Gpage
	page.GiCountRow = iCount

	iCountPage := (iCount / page.GiSize)
	if (iCount % page.GiSize) > 0 {
		iCountPage = iCountPage + 1
	}
	page.GiCountPage = iCountPage

	res := gorm.ScanRows2mapI(rows)

	if res == nil {
		return msgentity.Err(7003, "查询分页数量成功但解析数据发生异常")
	}

	page.SetRecord(res)

	return msgentity.Success(page, "查询分页数量成功")
}

// func (dao DaoBaseFunc) FindData(OrderInfoList orders, String sLikeStr, Object condition,
// 			onlyCreator bool, entity dbinfo.Entity) {

// 			}

// 取路径字段
func (dao DaoBaseFunc) GetPath(sId, dbName, tableName string) string {
	var build strings.Builder
	build.WriteString("SELECT sPath FROM ")
	build.WriteString(dbName)
	build.WriteString(tableName)
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.TableMajorKeyString)
	build.WriteString("=?")

	var sPath string
	dbResult := gorm.Raw(build.String(), sId).Scan(&sPath)
	if dbResult.Error != nil {
		Log.Error("查询路径信息发生异常:", dbResult.Error)
		return "/00/"
	}

	return sPath
}

/**
 * 取指定节点下的子节点编号
 * @param tableInfo 表信息
 * @param sPid 父节点
 * @return
 */
func (dao DaoBaseFunc) NewChildId(entity dbinfo.Entity, sPid string) *msgentity.MsgEntity {
	var build strings.Builder
	build.WriteString("SELECT (cur + 1) AS newId FROM (")
	build.WriteString(" 		select cast(A.${dbinfo.TableMajorKeyString} AS SIGNED) AS cur, IFNULL(")
	build.WriteString(" 			(select MIN( CAST(B.${dbinfo.TableMajorKeyString} as signed integer)) from ${sDbTableName} AS B")
	build.WriteString(" 				where cast(B.${dbinfo.TableMajorKeyString} AS SIGNED) > cast(A.${dbinfo.TableMajorKeyString} AS SIGNED)")
	build.WriteString(" 				and B.${dbinfo.TablePidKey} = #{sPid}")
	build.WriteString(" 				and CAST(B.${dbinfo.TableMajorKeyString} as signed integer) != 0")                                                         // 过滤字段中含非数字的记录
	build.WriteString(" 				and CAST(B.${dbinfo.TableMajorKeyString} as signed integer) = CAST(B.${dbinfo.TableMajorKeyString} as signed integer) +0") // 过滤字段中含非数字的记录
	build.WriteString(" 			), 99999999) AS nxt")
	build.WriteString(" 		from ${sDbTableName} AS A")
	build.WriteString(" 		where A.${dbinfo.TablePidKey} = #{sPid}")
	build.WriteString(" 		and CAST(A.${dbinfo.TableMajorKeyString} as signed integer) != 0")                                                         // 过滤字段中含非数字的记录
	build.WriteString(" 		and CAST(A.${dbinfo.TableMajorKeyString} as signed integer) = CAST(A.${dbinfo.TableMajorKeyString} as signed integer) +0") // 过滤字段中含非数字的记录
	build.WriteString(" 	) AS D")
	build.WriteString(" WHERE (nxt - cur > 1) or (nxt = 99999999)")
	build.WriteString(" ORDER BY cur")
	build.WriteString(" LIMIT 0, 1")

	txt := build.String()
	txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
	txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)
	txt = strings.Replace(txt, "${dbinfo.TablePidKey}", dbinfo.TablePidKey, -1)
	txt = strings.Replace(txt, "${dbinfo.TableMajorKeyString}", dbinfo.TableMajorKeyString, -1)
	txt = strings.Replace(txt, "#{sPid}", "@sPid", -1)

	newId := ""
	dbResult := gorm.Raw(txt, sql.Named(dbinfo.TablePidKey, sPid)).Find(&newId)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1001, "查询数据发生异常:", dbResult.Error)
	}

	return msgentity.Success(newId, "获取子节点编号成功")
}

/**
 * 验证新增数据是否存在重复
 * @param entity 数据实体
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) ValidEntityRepeatByAdd(entity dbinfo.Entity, currentUser string) *msgentity.MsgEntity {
	customService := serviceMap[dbinfo.SimpleTableName(entity)]

	//-- 树形结构 --//
	if dbinfo.EntityHasPid(entity) {
		if nil == customService { //如果没有自定义业务层
			return dao.CommonCheckRepeatByAddAndTree(entity, currentUser) //通用树型结构表添加数据时重复检查方法
		}

		method := reflectutil.GetMethod(customService, "CheckRepeatByAddAndTree")
		if !method.IsValid() { //如果自定义业务层定义了自检方法
			return dao.CommonCheckRepeatByAddAndTree(entity, currentUser) //通用树型结构表添加数据时重复检查方法
		}

		result := reflectutil.DoMethod(customService, "CheckRepeatByAddAndTree", entity)
		me := result[0].Interface()
		return me.(*msgentity.MsgEntity)
	}

	//--不是树形数据则使用普通方法检查--//
	if nil == customService { //如果没有自定义业务层
		return dao.CommonCheckRepeatByAdd(entity, currentUser) //通用添加数据时重复检查方法
	}

	method := reflectutil.GetMethod(customService, "CheckRepeatByAdd")
	if !method.IsValid() { //如果自定义业务层定义了自检方法
		return dao.CommonCheckRepeatByAdd(entity, currentUser) //通用添加数据时重复检查方法
	}

	result := reflectutil.DoMethod(customService, "CheckRepeatByAdd", entity)
	me := result[0].Interface()
	return me.(*msgentity.MsgEntity)
}

/**
 * 验证更新数据是否存在重复
 * @param entity 数据实体
 * @param id 主键
 * @param data 数据
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) ValidEntityRepeatByEdit(entity dbinfo.Entity, id interface{}, data map[string]interface{}, currentUser string) *msgentity.MsgEntity {
	customService := serviceMap[dbinfo.SimpleTableName(entity)]

	//-- 树形结构 --//
	if dbinfo.EntityHasPid(entity) {
		if nil == customService { //如果没有自定义业务层
			return dao.CommonCheckRepeatByEditAndTree(entity, id, data["sName"], currentUser) //通用树型结构表添加数据时重复检查方法
		}

		method := reflectutil.GetMethod(customService, "CheckRepeatByEditAndTree")
		if !method.IsValid() { //如果自定义业务层定义了自检方法
			return dao.CommonCheckRepeatByEditAndTree(entity, id, data["sName"], currentUser) //通用树型结构表添加数据时重复检查方法
		}

		result := reflectutil.DoMethod(customService, "CheckRepeatByEditAndTree", id, data["sName"])
		me := result[0].Interface()
		return me.(*msgentity.MsgEntity)
	}

	//--不是树形数据则使用普通方法检查--//
	if nil == customService { //如果没有自定义业务层
		return dao.CommonCheckRepeatByEdit(entity, id, currentUser) //通用添加数据时重复检查方法
	}

	method := reflectutil.GetMethod(customService, "CheckRepeatByEdit")
	if !method.IsValid() { //如果自定义业务层定义了自检方法
		return dao.CommonCheckRepeatByEdit(entity, id, currentUser) //通用添加数据时重复检查方法
	}

	result := reflectutil.DoMethod(customService, "CheckRepeatByEdit", data, id)
	me := result[0].Interface()
	return me.(*msgentity.MsgEntity)
}

/**
 * 通用树型结构表添加数据时重复检查方法
 * @param entity 数据实体
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) CommonCheckRepeatByAddAndTree(entity dbinfo.Entity, currentUser string) *msgentity.MsgEntity {
	vName := dbinfo.GetVal(entity, dbinfo.TableTreeNodeName)
	if nil == vName {
		return msgentity.Err(1001, "节点名称为空")
	}

	sName := vName.(string)

	var sPid string
	vPid := dbinfo.GetVal(entity, dbinfo.TablePidKey)
	if nil != vPid {
		sPid = vPid.(string)
	} else {
		sPid = dbinfo.TableTreeRootValue
	}

	if sPid == "" {
		sPid = dbinfo.TableTreeRootValue
	}

	//同一层节点下,展现名不能相同//
	var build strings.Builder
	build.WriteString("SELECT SUM(iCount) AS iCount FROM (")
	build.WriteString(" 	select count(1) as iCount from ${sDbTableName}")
	build.WriteString(" 	where ${dbinfo.TablePidKey} = #{sPid} and ${dbinfo.TableTreeNodeName} = #{sName}")
	build.WriteString(") TMP")

	txt := build.String()
	txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
	txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)
	txt = strings.Replace(txt, "${dbinfo.TablePidKey}", dbinfo.TablePidKey, -1)
	txt = strings.Replace(txt, "${dbinfo.TableTreeNodeName}", dbinfo.TableTreeNodeName, -1)
	txt = strings.Replace(txt, "#{sPid}", "@sPid", -1)
	txt = strings.Replace(txt, "#{sName}", "@sName", -1)

	var iCount int
	dbResult := gorm.Raw(txt, sql.Named(dbinfo.TablePidKey, sPid), sql.Named("sName", sName)).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1002, "查询数据发生异常:", dbResult.Error)
	}

	if iCount != 0 {
		return msgentity.Err(1003, "节点重复")
	}

	return msgentity.Success(1999, "节点未重复")
}

/**
 * 通用树型结构表添加数据时重复检查方法
 * @param entity 数据实体
 * @param id 主键
 * @param sName 展现名
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) CommonCheckRepeatByEditAndTree(entity dbinfo.Entity, id interface{}, sName interface{}, currentUser string) *msgentity.MsgEntity {
	if (sName == nil) || (sName == "") || (sName == "<nil>") {
		return msgentity.Err(1001, "节点名称为空")
	}

	//同一层节点下,展现名不能相同//
	var build strings.Builder
	build.WriteString("SELECT SUM(iCount) AS iCount FROM (")
	build.WriteString(" 	select count(1) as iCount from ${sDbTableName}")
	build.WriteString(" 	where ${sId} <> @sId")
	build.WriteString(" 	and ${dbinfo.TablePidKey} = (select a.${dbinfo.TablePidKey} from ${sDbTableName} a where a.${sId} = #{sId})")
	build.WriteString(" 	and ${dbinfo.TableTreeNodeName} = #{sName}")
	build.WriteString(") TMP")

	txt := build.String()
	txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
	txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)
	txt = strings.Replace(txt, "${sId}", dbinfo.EntityKeyName(entity), -1)
	txt = strings.Replace(txt, "${dbinfo.TablePidKey}", dbinfo.TablePidKey, -1)
	txt = strings.Replace(txt, "${dbinfo.TableTreeNodeName}", dbinfo.TableTreeNodeName, -1)
	txt = strings.Replace(txt, "#{sName}", "@sName", -1)

	var iCount int
	dbResult := gorm.Raw(txt, sql.Named(dbinfo.EntityKeyName(entity), id), sql.Named("sName", sName)).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1002, "查询数据发生异常:", dbResult.Error)
	}

	if iCount != 0 {
		return msgentity.Err(1003, "节点重复")
	}

	return msgentity.Success(1999, "节点未重复")
}

/**
 * 通用添加数据时重复检查方法
 * @param entity 数据实体
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) CommonCheckRepeatByAdd(entity dbinfo.Entity, currentUser string) *msgentity.MsgEntity {

	vCheckRepeatCombination := checkRepeatCombinationMap[dbinfo.SimpleTableName(entity)]
	vCheckRepeatAlone := checkRepeatAloneMap[dbinfo.SimpleTableName(entity)]

	k := 0

	//检查待新增内容是否存在重复数据(多字段组合重复即重复)集合
	if (vCheckRepeatCombination != nil) && (len(vCheckRepeatCombination) > 0) {
		checkRepeatCombination := vCheckRepeatCombination

		var build strings.Builder
		build.WriteString("SELECT COUNT(1) AS iCount FROM ${sDbTableName} WHERE 1=1")

		var temp strings.Builder
		temp.WriteString("[")

		where := make(map[string]interface{})
		for _, value := range checkRepeatCombination {
			build.WriteString(" AND ")
			build.WriteString(value)
			build.WriteString(" = @")
			build.WriteString(value)

			where[value] = dbinfo.GetVal(entity, value)

			dataInfo := entity.GetDataInfo(value)
			temp.WriteString("、'")
			temp.WriteString(dataInfo.GsComment)
			temp.WriteString("'")
		}

		if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
			build.WriteString(" AND ")
			build.WriteString(dbinfo.TableDelSignName)
			build.WriteString(" != 1")
		}

		txt := strings.Replace(build.String(), "1=1 AND ", "", -1)
		txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
		txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return msgentity.Err(1001, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			temp.WriteString("]组合发现数据重复")
			return msgentity.Err(1002, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	//检查待新增内容是否存在重复数据(单独字段重复即重复)集合
	if (vCheckRepeatAlone != nil) && (len(vCheckRepeatAlone) > 0) {
		checkRepeatAlone := vCheckRepeatAlone

		var build strings.Builder
		build.WriteString("SELECT SUM(iCount) FROM (")

		where := make(map[string]interface{})
		for key, value := range checkRepeatAlone {
			build.WriteString(" union all select (SIGN(COUNT(1)) * ")
			build.WriteString(strconv.Itoa(value))
			build.WriteString(") as iCount ")
			build.WriteString(" from ${sDbTableName} ")
			build.WriteString(" where ")
			build.WriteString(key)
			build.WriteString("= @")
			build.WriteString(key)

			if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
				build.WriteString(" and ")
				build.WriteString(dbinfo.TableDelSignName)
				build.WriteString(" != 1")
			}

			where[key] = dbinfo.GetVal(entity, key)
		}

		build.WriteString(") TMP")

		txt := strings.Replace(build.String(), " union all ", " ", 1)
		txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
		txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return msgentity.Err(1003, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			var temp strings.Builder
			str := fmt.Sprintf("%0*d", len(checkRepeatAlone), iCount)
			array := []rune(str)

			for key, value := range checkRepeatAlone {
				i := len(strconv.Itoa(value))
				if array[i] != 0 {
					continue
				}

				dataInfo := entity.GetDataInfo(key)
				temp.WriteString("、'")
				temp.WriteString(dataInfo.GsComment)
				temp.WriteString("'")
			}

			temp.WriteString("存在重复")

			return msgentity.Err(1004, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	if k == 0 {
		return msgentity.Success("没有设定验证函数,通过")
	}

	return msgentity.Success("经验证,通过")
}

/**
 * 通用更新数据时重复检查方法
 * @param entity 数据实体
 * @param id 数据主键
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) CommonCheckRepeatByEdit(entity dbinfo.Entity, id interface{}, currentUser string) *msgentity.MsgEntity {

	vCheckRepeatCombination := checkRepeatCombinationMap[dbinfo.SimpleTableName(entity)]
	vCheckRepeatAlone := checkRepeatAloneMap[dbinfo.SimpleTableName(entity)]

	k := 0

	//检查待新增内容是否存在重复数据(多字段组合重复即重复)集合
	if (vCheckRepeatCombination != nil) && (len(vCheckRepeatCombination) > 0) {
		checkRepeatCombination := vCheckRepeatCombination

		var build strings.Builder
		build.WriteString("SELECT COUNT(1) AS iCount FROM ${sDbTableName} WHERE 1=1")

		var temp strings.Builder
		temp.WriteString("[")

		where := make(map[string]interface{})
		where[dbinfo.EntityKeyName(entity)] = id
		build.WriteString(" AND ")
		build.WriteString(dbinfo.EntityKeyName(entity))
		build.WriteString(" != @")
		build.WriteString(dbinfo.EntityKeyName(entity))

		for _, value := range checkRepeatCombination {
			build.WriteString(" AND ")
			build.WriteString(value)
			build.WriteString(" = @")
			build.WriteString(value)

			where[value] = dbinfo.GetVal(entity, value) //利用反射取属性值

			dataInfo := entity.GetDataInfo(value)
			temp.WriteString("、'")
			temp.WriteString(dataInfo.GsComment)
			temp.WriteString("'")
		}

		if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
			build.WriteString(" AND ")
			build.WriteString(dbinfo.TableDelSignName)
			build.WriteString(" != 1")
		}

		txt := strings.Replace(build.String(), "1=1 AND ", "", -1)
		txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
		txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return msgentity.Err(1001, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			temp.WriteString("]组合发现数据重复")
			return msgentity.Err(1002, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	//检查待新增内容是否存在重复数据(单独字段重复即重复)集合
	if (vCheckRepeatAlone != nil) && (len(vCheckRepeatAlone) > 0) {
		checkRepeatAlone := vCheckRepeatAlone

		var build strings.Builder
		build.WriteString("SELECT SUM(iCount) FROM (")

		where := make(map[string]interface{})
		where[dbinfo.EntityKeyName(entity)] = id

		for key, value := range checkRepeatAlone {
			build.WriteString(" union all select (SIGN(COUNT(1)) * ")
			build.WriteString(strconv.Itoa(value))
			build.WriteString(") as iCount ")
			build.WriteString(" from ${sDbTableName} ")
			build.WriteString(" where ")
			build.WriteString(key)
			build.WriteString("= @")
			build.WriteString(key)
			build.WriteString(" and ")
			build.WriteString(dbinfo.EntityKeyName(entity))
			build.WriteString(" != @")
			build.WriteString(dbinfo.EntityKeyName(entity))

			if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
				build.WriteString(" and ")
				build.WriteString(dbinfo.TableDelSignName)
				build.WriteString(" != 1")
			}

			where[key] = dbinfo.GetVal(entity, key)
		}

		build.WriteString(") TMP")

		txt := strings.Replace(build.String(), " union all ", " ", 1)
		txt = strings.Replace(txt, "${sDbTableName}", entity.TableName(), -1)
		txt = strings.Replace(txt, "${sTableName}", entity.OwnerTable(), -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return msgentity.Err(1003, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			var temp strings.Builder
			str := fmt.Sprintf("%0*d", len(checkRepeatAlone), iCount)
			array := []rune(str)

			for key, value := range checkRepeatAlone {
				i := len(strconv.Itoa(value))
				if array[i] != 0 {
					continue
				}

				dataInfo := entity.GetDataInfo(key)
				temp.WriteString("、'")
				temp.WriteString(dataInfo.GsComment)
				temp.WriteString("'")
			}

			temp.WriteString("存在重复")

			return msgentity.Err(1004, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	if k == 0 {
		return msgentity.Success("没有设定验证函数,通过")
	}

	return msgentity.Success("经验证,通过")
}

/**
 * 读取树形结构数据
 * @param entity 数据实体
 * @param sGroupColumn 分组字段
 * @param sGroupName 分组名称
 * @param currentUser 当前用户
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindByTree(entity dbinfo.Entity, sGroupColumn, sGroupName, currentUser string) *msgentity.MsgEntity {
	if !dbinfo.HasColumnName(entity, sGroupName) {
		return msgentity.Err(1001, "指定分组字段不存在！")
	}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.TableMajorKeyString)
	build.WriteString(" > 0")

	where := make(map[string]interface{})
	if sGroupName != "" {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TablePathKey)
		build.WriteString(" LIKE (")
		build.WriteString(" 	select CONCAT(a.")
		build.WriteString(dbinfo.TablePathKey)
		build.WriteString(", '%')")
		build.WriteString(" 	from ${sDbTableName} a")

		if sGroupColumn != "" {
			build.WriteString(" 	where a.")
			build.WriteString(sGroupColumn) //指定字段作为分组标识
			build.WriteString(" = ?")
		} else if dbinfo.EntityHasOnlyign(entity) {
			build.WriteString(" 	where a.")            //启用唯一标识作为关键字
			build.WriteString(dbinfo.TableOnlyignName) //启用唯一标识作为关键字
			build.WriteString(" = @sGroupName")        //启用唯一标识作为关键字
		} else {
			build.WriteString(" 	where a.")
			build.WriteString(dbinfo.TableTreeNodeName)
			build.WriteString(" = @sGroupName")
		}

		build.WriteString(" )")
		where["sGroupName"] = sGroupName
	}

	build.WriteString(" ORDER BY ")
	build.WriteString(dbinfo.TablePathKey)

	rows, err := gorm.Raw(build.String(), where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(1002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return msgentity.Err(1003, "查询后数据转换发生异常")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 根据字段名取指定记录编号的数据库表中对应字段的值
 * @param entity 实体类
 * @param id 记录编号
 * @param fieldNames 待取数据的字段名称集合
 * @param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return msgentity.MsgEntity 返回内容data中存放的是Map
 */
func (dao DaoBaseFunc) GetValueByFieldName(entity dbinfo.Entity, id interface{}, fieldNames []string, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	fieldNames = dao.holdByEntityToArray(entity, fieldNames) //按实体保留数组中的数据
	if len(fieldNames) < 1 {
		return msgentity.Err(7001, "没有对应的数据可查询！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")

	for _, val := range fieldNames {
		build.WriteString(",")
		build.WriteString(val)
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("=@")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[dbinfo.EntityKeyName(entity)] = id

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7003, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7004, "数据不存在！")
	}

	return msgentity.Success(res[0], "查询成功")
}

/**
 * 根据字段名取指定记录编号的数据库表中对应字段的值
 * @param entity 实体类
 * @param id 记录编号
 * @param fieldName 待取数据的字段名称集合
 * @param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return msgentity.MsgEntity 返回内容data中存放的是Map
 */
func (dao DaoBaseFunc) GetValueByField(entity dbinfo.Entity, id interface{}, fieldName, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	fieldName = strings.TrimSpace(fieldName)
	if fieldName == "" {
		return msgentity.Err(7001, "没有对应的数据可查询！")
	}

	columns := strings.Split(fieldName, ",")
	columns = dao.holdByEntityToArray(entity, columns)
	if len(columns) < 1 {
		return msgentity.Err(7002, "没有对应的字段数据可查询！")
	}

	fieldName = ""
	for _, val := range columns {
		temp := strings.TrimSpace(val)
		if temp == "" {
			continue
		}

		fieldName = fieldName + "," + temp
	}

	if fieldName == "" {
		return msgentity.Err(7003, "没有对应的字段数据可查询！")
	}

	fieldName = fieldName[1:]

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(fieldName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" = @")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[dbinfo.EntityKeyName(entity)] = id

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7004, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7005, "数据不存在！")
	}

	return msgentity.Success(res[0], "查询成功")
}

/**
 * 根据字段名取指定条件的数据库表中对应字段的值
 * @param entity 实体类
 * @param whereInfo 条件
 * @param fieldName 待取数据的字段名称集合
 * @param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return msgentity.MsgEntity 返回内容data中存放的是Map
 */
func (dao DaoBaseFunc) GetValueByWhere(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	fieldName = strings.TrimSpace(fieldName)
	if fieldName == "" {
		return msgentity.Err(7001, "没有对应的数据可查询！")
	}

	if !dbinfo.HasColumnName(entity, fieldName) {
		return msgentity.Err(7002, "指定字段不存在！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(fieldName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := make(map[string]interface{})
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	sql = strings.Replace(sql, " 1=1 AND ", " ", -1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)
	rows, err := gorm.Raw(sql, where).Rows()
	if nil != err {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7004, "查询发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7005, "数据不存在！")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 取记录对应的版本号
 * @param entity 实体类
 * @param idName 编号
 * @return
 */
func (dao DaoBaseFunc) GetiVersion(entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
	if fmt.Sprintf("%v", id) == "" {
		return msgentity.Err(7001, "记录编号参数为空！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.TableVersionName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("=@")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[dbinfo.EntityKeyName(entity)] = id

	iVersion := 0
	dbResult := gorm.Raw(build.String(), where).Find(&iVersion)
	if dbResult.Error != nil {
		Log.Error("验证数据是否重复发生异常:", dbResult.Error)
		return msgentity.Err(7002, "验证数据是否重复发生异常:", dbResult.Error)
	}

	if iVersion == 0 {
		return msgentity.Err(7003, "没有发现此数据")
	}

	return msgentity.Success(iVersion, "查询成功")
}

/**
 * 取记录对应的状态值
 * @param entity 实体类
 * @param id 编号
 * @return
 */
func (dao DaoBaseFunc) GetiState(entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
	if fmt.Sprintf("%v", id) == "" {
		return msgentity.Err(7001, "记录编号参数为空！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(dbinfo.TableStateName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString("=@")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[dbinfo.EntityKeyName(entity)] = id

	iState := 0
	dbResult := gorm.Raw(build.String(), where).Find(&iState)
	if dbResult.Error != nil {
		Log.Error("验证数据是否重复发生异常:", dbResult.Error)
		return msgentity.Err(7002, "验证数据是否重复发生异常:", dbResult.Error)
	}

	if iState == 0 {
		return msgentity.Err(7003, "没有发现此数据")
	}

	return msgentity.Success(iState, "查询成功")
}

/**
 * 根据关键值取对象集合
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @Param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7002, "没有对应的查询条件！")
	}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)
	rows, iCode, err := gorm.FindToMap(sql, where)
	if err != nil {
		return msgentity.Err(iCode, err.Error())
	}

	return msgentity.Success(rows, "查询成功")
}

/**
 * 根据关键值取对象集合中的第一个
 * @Param entity 实体类
 * @Param whereInfo 存放查询条件
 * @Param currentUser 当前用户
 * @param onlyCreator 是否只取当前用户创建的数据
 * @param fields 指定要查询的字段集合
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindOneByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool, fields ...string) *msgentity.MsgEntity {
	columns := "," + entity.BaseColumnNames() + ","
	whereInfoTemp := []dbinfo.WhereInfo{}
	for _, val := range whereInfo {
		if !strings.Contains(columns, ","+val.Name+",") {
			continue
		}

		whereInfoTemp = append(whereInfoTemp, val)
	}

	if len(whereInfoTemp) < 1 {
		return msgentity.Err(7001, "没有对应的查询条件！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")

	fields = dao.holdByEntityToArray(entity, fields) //按实体保留数组中的数据
	if len(fields) < 1 {
		return msgentity.Err(7002, "没有对应的字段数据可查询！")
	}

	for _, val := range fields {
		build.WriteString(",")
		build.WriteString(val)
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfoTemp {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), "SELECT ,", "SELECT ", -1)
	text = strings.Replace(text, " 1=1 AND ", " ", -1)
	text = strings.Replace(text, " WHERE 1=1", " ", -1)
	data, iCode, err := gorm.FindToMap(text, where)
	if err != nil {
		return msgentity.Err(iCode, err)
	}

	if iCode < 1 {
		return msgentity.Err(7004, "数据不存在！")
	}

	return msgentity.Success(data[0], "查询成功")
}

/**
 * 根据关键值取对象集合中的符合条件的第一条记录的指定字段
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @param fieldName 指定要查询的字段
 * @param currentUser 当前用户
 * @param onlyCreator 仅查询创建者
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindValueByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7002, "没有对应的查询条件！")
	}

	fieldName = strings.TrimSpace(fieldName)
	if fieldName == "" {
		return msgentity.Err(7002, "没有待查字段！")
	}

	if !dbinfo.HasColumnName(entity, fieldName) {
		return msgentity.Err(7003, "指定字段不存在！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(fieldName)
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), " 1=1 AND ", " ", -1)
	text = strings.Replace(text, " WHERE 1=1", " ", -1) //没有条件
	rows, iCount, err := gorm.FindToMap(text, where)
	if err != nil {
		return msgentity.Err(iCount, err.Error())
	}

	if iCount < 1 {
		return msgentity.Err(7006, "数据不存在！")
	}

	val := rows[0][fieldName]

	return msgentity.Success(val, "查询成功")
}

/**
 * 根据关键值取对象集合中的符合条件的第一条记录的指定字段
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @param fieldMap 指定要查询的字段集合(原字段, 别名)
 * @param currentUser 当前用户
 * @param onlyCreator 仅查询创建者
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindByFields(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldMap map[string]string, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7001, "没有对应的查询条件！")
	}

	var columns strings.Builder
	columns.WriteString("@@@")
	var orderStr strings.Builder
	orderStr.WriteString("@@@")

	iCount := 0
	for k, v := range fieldMap {
		if !dbinfo.HasColumnName(entity, k) {
			continue
		}

		iCount++

		columns.WriteString(",")
		columns.WriteString(k)

		orderStr.WriteString(",")
		orderStr.WriteString(k)

		if v != "" {
			columns.WriteString(" AS ")
			columns.WriteString(v)
		}
	}

	if iCount < 1 {
		return msgentity.Err(7003, "没有符合的字段！")
	}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(strings.Replace(columns.String(), "@@@,", "", -1))
	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	build.WriteString(" ORDER BY ")
	build.WriteString(strings.Replace(orderStr.String(), "@@@,", "", -1))

	text := strings.Replace(build.String(), " WHERE 1=1 AND ", " WHERE ", -1)
	text = strings.Replace(text, " WHERE 1=1", " ", -1)

	rows, err := gorm.Raw(text, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7004, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7005, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7006, "数据不存在！")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 根据关键值查数量
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 仅查询创建者
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) FindCountByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7001, "没有对应的查询条件！")
	}

	var build strings.Builder
	build.WriteString("SELECT COUNT(1) AS iCount FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7003, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7004, "数据不存在！")
	}

	return msgentity.Success(res[0]["iCount"], "查询成功")
}

/**
 * 以事务方式执行多个sql
 * 注意:Mapper必须存在才能执行
 * @param sqls [sql, params]
 * @return msgentity.MsgEntity 一个执行失败则回滚
 */
func (dao DaoBaseFunc) TransactionSql(sqls map[string]map[string]interface{}) *msgentity.MsgEntity {
	if len(sqls) < 1 {
		return msgentity.Err(7001, "没有需要执行的sql")
	}

	tx := gorm.GetDB().Begin() // 开始事务

	for sql, params := range sqls {
		if err := tx.Exec(sql, params).Error; err == nil {
			continue
		}

		Log.Error("sql执行失败:", sql)
		tx.Rollback() //回滚事务
		return msgentity.Err(7002, "没有需要执行的sql")
	}

	tx.Commit() //提交事务

	return msgentity.Success(7999, "事务执行成功")
}

/**
 * 根据字段名取分组数据
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param fields 字段名与别名对象
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @return
 */
func (dao DaoBaseFunc) GroupByField(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	return dao.GroupByFieldBase(entity, sCreator, fields, currentUser, onlyCreator, false)
}

/**
 * 根据字段名取分组数据,并返回数量
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param fields 字段名与别名对象
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @return
 */
func (dao DaoBaseFunc) GroupByFieldAndCount(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	return dao.GroupByFieldBase(entity, sCreator, fields, currentUser, onlyCreator, true)
}

/**
 * 根据字段名取分组数据
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param fields 字段名与别名对象
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @param isGroupCount 添加分组后是否添加'数量列'
 * @return
 */
func (dao DaoBaseFunc) GroupByFieldBase(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator, isGroupCount bool) *msgentity.MsgEntity {
	if len(fields) < 1 {
		return msgentity.Err(7001, "没有对应的待查字段！")
	}

	array := map[string]interface{}{}
	for key, value := range fields {
		array[key] = value
	}

	array = reflectutil.HoldByEntity(entity, array, "", "G") //按实体保留map中的数据

	var build strings.Builder
	build.WriteString("SELECT @@")

	for key, val := range array {
		build.WriteString(",")
		build.WriteString(key)

		if val.(string) != "" {
			build.WriteString(" AS ")
			build.WriteString(val.(string))
		}
	}

	if isGroupCount {
		build.WriteString(",")
		build.WriteString(" COUNT(1) AS iCount")
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	if sCreator != "" {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
	}

	where := map[string]interface{}{}
	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	build.WriteString(" GROUP BY @@")

	for key := range fields {
		build.WriteString(",")
		build.WriteString(key)
	}

	sql := build.String()
	sql = strings.Replace(sql, " WHERE 1=1 GROUP BY ", " GROUP BY ", -1)
	sql = strings.Replace(sql, " @@,", " ", -1)
	sql = strings.Replace(sql, " 1=1 AND ", " ", -1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7004, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7005, "数据不存在！")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 取表中指定字段的最大值
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param field 字段名
 * @param where 查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) MaxByField(entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	field = strings.TrimSpace(field)
	if field == "" {
		return msgentity.Err(7001, "没有待查字段！")
	}

	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7002, "没有对应的查询条件！")
	}

	if !dbinfo.HasColumnName(entity, field) {
		return msgentity.Err(7003, "指定字段不存在！")
	}

	var build strings.Builder
	build.WriteString("SELECT MAX(")
	build.WriteString(field)
	build.WriteString(") AS data FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if sCreator == "" {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7004, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7005, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7006, "数据不存在！")
	}

	return msgentity.Success(res[0]["data"], "查询成功")
}

/**
 * 取表中指定字段的最小值
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param field 字段名
 * @param where 查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @param whereStr 查询条件字符串
 * @return
 */
func (dao DaoBaseFunc) MinByField(entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	field = strings.TrimSpace(field)
	if field == "" {
		return msgentity.Err(7001, "没有待查字段！")
	}

	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7002, "没有对应的查询条件！")
	}

	if !dbinfo.HasColumnName(entity, field) {
		return msgentity.Err(7003, "指定字段不存在！")
	}

	var build strings.Builder
	build.WriteString("SELECT MIN(")
	build.WriteString(field)
	build.WriteString(") AS data FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if sCreator == "" {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7004, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return msgentity.Err(7005, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7006, "数据不存在！")
	}

	return msgentity.Success(res[0]["data"], "查询成功")
}

/**
 * 检查关键值记录是否存在(返回1:存在;0:不存在)
 * @param entity 实体类
 * @param id 记录编号
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) HasById(entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
	if fmt.Sprintf("%v", id) == "" {
		return msgentity.Err(7001, "记录编号参数为空！")
	}

	var build strings.Builder
	build.WriteString("SELECT COUNT(1) AS iCount FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(dbinfo.EntityKeyName(entity))
	build.WriteString(" =@")
	build.WriteString(dbinfo.EntityKeyName(entity))

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := map[string]interface{}{dbinfo.EntityKeyName(entity): id}

	var iCount int
	dbResult := gorm.Raw(build.String(), where).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(7003, "查询数据发生异常:", dbResult.Error)
	}

	if iCount == 0 {
		return msgentity.Err(0, "数据不存在！")
	}

	return msgentity.Success(1, "数据存在！")
}

/**
 * 检查关键值记录是否存在(返回1:存在;0:不存在)
 * @param entity 实体类
 * @Param keyName 字段名
 * @Param keyValue 字段值
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) HasByKey(entity dbinfo.Entity, keyName string, keyValue interface{}) *msgentity.MsgEntity {
	keyName = strings.TrimSpace(keyName)
	if keyName == "" {
		return msgentity.Err(7001, "字段名参数为空！")
	}

	if (keyValue == nil) || (fmt.Sprintf("%v", keyValue) == "") || (fmt.Sprintf("%v", keyValue) == "<nil>") {
		return msgentity.Err(7002, "字段值参数为空！")
	}

	if !dbinfo.HasColumnName(entity, keyName) {
		return msgentity.Err(7003, "指定字段不存在！")
	}

	dataInfo := entity.GetDataInfo(keyName)
	if nil == dataInfo {
		return msgentity.Err(7004, "字段备注信息缺失")
	}

	switch dataInfo.GsDbFileType {
	case "int":
		temp, err := strconv.Atoi(keyValue.(string))
		if err != nil {
			return msgentity.Err(7005, "字段值参数为不符合规范！")
		}
		keyValue = temp
	case "bigint":
		temp, err := strconv.ParseInt(keyValue.(string), 10, 64)
		if err != nil {
			return msgentity.Err(7006, "字段值参数为不符合规范！")
		}
		keyValue = temp
	}

	var build strings.Builder
	build.WriteString("SELECT COUNT(1) AS iCount FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE ")
	build.WriteString(keyName)
	build.WriteString(" =@")
	build.WriteString(keyName)

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := map[string]interface{}{keyName: keyValue}

	var iCount int
	dbResult := gorm.Raw(build.String(), where).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(7007, "查询数据发生异常:", dbResult.Error)
	}

	if iCount == 0 {
		return msgentity.Err(0, "数据不存在！")
	}

	return msgentity.Success(1, "数据存在！")
}

/**
 * 执行SQL脚本获取单行单列数据
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) DoSql(sql string, where ...interface{}) *msgentity.MsgEntity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1002, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return msgentity.Err(1003, "查询成功但没有数据")
	}

	return msgentity.Success(list, "查询成功")
}

/**
 * 执行SQL脚本获取单行单列数据
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) ExecSql(sql string, where ...interface{}) *msgentity.MsgEntity {
	txt := gorm.ReplaceVariable(sql)

	dbResult := gorm.Exec(txt, where...)
	if dbResult.Error != nil {
		Log.Error("执行发生异常:", dbResult.Error)
		return msgentity.Err(1001, "执行发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(1002, "执行成功但没有影响数")
	}

	return msgentity.Success(dbResult.RowsAffected, "执行成功")
}

/**
 * 执行SQL脚本获取单行单列数据
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) GetValue(sql string, where ...interface{}) *msgentity.MsgEntity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1002, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return msgentity.Err(1003, "查询成功但没有数据")
	}

	var result interface{}
	row := list[0]
	for _, v := range row {
		result = v
	}

	return msgentity.Success(result, "查询成功")
}

/**
 * 执行SQL脚本获取一行数据(多列)
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) GetRow(sql string, where ...interface{}) *msgentity.MsgEntity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1001, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return msgentity.Err(1002, "查询成功但没有数据")
	}

	return msgentity.Success(list[0], "查询成功")
}

/**
 * 执行SQL脚本获取多行数据(多列)
 * 注意:库名必须用${}进行包装,此脚本可返回多条记录
 * @param sql SQL脚本
 * @param where 存放查询条件
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) GetRows(sql string, where ...interface{}) *msgentity.MsgEntity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return msgentity.Err(1001, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return msgentity.Err(1002, "查询成功但没有数据")
	}

	return msgentity.Success(list, "查询成功")
}

/**
 * 根据关键值翻转值(限布尔值类型,1转2,2转1)
 * @Param entity 实体类
 * @Param whereInfo 存放查询条件
 * @Param reversalColumn 翻转的字段名
 * @Param currentUser 当前用户
 * @Param onlyCreator 是否只翻转创建人创建的数据
 * @return msgentity.MsgEntity
 */
func (dao DaoBaseFunc) ReversalByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, reversalColumn, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return msgentity.Err(7001, "没有对应的查询条件！")
	}

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(entity.TableName())
	build.WriteString(" SET ")
	build.WriteString(reversalColumn)
	build.WriteString("= IF(")
	build.WriteString(reversalColumn)
	build.WriteString("=1,2,1)")
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)

	dbResult := gorm.Exec(sql, where)
	if dbResult.Error != nil {
		Log.Error("执行发生异常:", dbResult.Error)
		return msgentity.Err(1001, "执行发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return msgentity.Err(1002, "执行成功但没有影响数")
	}

	return msgentity.Success(dbResult.RowsAffected, "执行成功")
}

/**
 * 根据条件仅查询指定字段名数据
 * @param entity 实体类
 * @param whereInfo
 * @param fieldNames 待取数据的字段名称集合
 * @Param currentUser 当前用户
 * @Param onlyCreator 是否只翻转创建人创建的数据
 * @return msgentity.MsgEntity 返回内容data中存放的是Map
 */
func (dao DaoBaseFunc) FindField(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldNames []string, currentUser string, onlyCreator bool) *msgentity.MsgEntity {
	fieldNames = dao.holdByEntityToArray(entity, fieldNames) //按实体保留数组中的数据
	if len(fieldNames) < 1 {
		return msgentity.Err(7001, "没有对应的数据可查询！")
	}

	whereInfo = dao.holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件

	var build strings.Builder
	build.WriteString("SELECT ")

	for _, val := range fieldNames {
		build.WriteString(",")
		build.WriteString(val)
	}

	build.WriteString(" FROM ")
	build.WriteString(entity.TableName())
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(dbinfo.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	sql = strings.Replace(sql, " WHERE 1=1 AND ", " WHERE ", -1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)

	rows, err := gorm.Raw(sql, where).Rows()
	if nil != err {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询发生异常:", err)
		return msgentity.Err(7003, "查询发生异常:", err)
	}

	if len(res) < 1 {
		return msgentity.Err(7004, "数据不存在！")
	}

	return msgentity.Success(res, "查询成功")
}

/**
 * 按实体保留切片中的数据
 * object 待检查对象
 * whereInfo 数据
 */
func (DaoBaseFunc) holdByEntityToWhereInfo(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) []dbinfo.WhereInfo {
	columns := "," + entity.BaseColumnNames() + ","
	result := []dbinfo.WhereInfo{}
	for _, val := range whereInfo {
		if !strings.Contains(columns, ","+val.Name+",") {
			continue
		}

		result = append(result, val)
	}

	return result
}

/**
 * 按实体保留切片中的数据
 * object 待检查对象
 * data 数据
 * fieldPrefix 字段前缀(可不传)
 */
func (DaoBaseFunc) holdByEntityToArray(entity dbinfo.Entity, data []string) []string {
	columns := "," + entity.BaseColumnNames() + ","
	result := []string{}
	for _, val := range data {
		if !strings.Contains(columns, ","+val+",") {
			continue
		}

		result = append(result, val)
	}

	return result
}

// 分页数据查询部分语句,在分页查询数据及 数据搜索时使用
// 返回 findByPageCountSql, findByPageSql, params
func (dao DaoBaseFunc) GetFindByPageSelectSql(currentUser string, entity dbinfo.Entity,
	findByPageParam dbinfo.FindByPageParam, onlyCreator bool) (string, string, map[string]interface{}) {
	conditionMap := map[string]interface{}{}                       //普通条件
	conditionRangeStMap := map[string]interface{}{}                //范围条件
	conditionRangeEdMap := map[string]interface{}{}                //范围条件
	conditionArrayMap := map[string]string{}                       //数组条件
	conditionLikeMap := []string{}                                 //模糊查询字段
	sLikeStr := strings.TrimSpace(findByPageParam.GsLikeStr)       //全文检索条件
	sLikeDateSt := strings.TrimSpace(findByPageParam.GsLikeDateSt) //模糊查询记录修改时间范围条件-开始
	sLikeDateEd := strings.TrimSpace(findByPageParam.GsLikeDateEd) //模糊查询记录修改时间范围条件-结束

	params := map[string]interface{}{}

	var appendFieldSql strings.Builder
	var dictionarySql strings.Builder
	var oTherJoin map[string]string

	// var s reflect.Type
	// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
	// if typeOf.Kind() == reflect.Ptr { //是否指针类型
	// 	s = reflect.TypeOf(entity).Elem() //通过反射获取type定义
	// } else if "reflect.Value" == typeOf.String() {
	// 	if entity.(reflect.Value).Kind() == reflect.Ptr {
	// 		s = entity.(reflect.Value).Elem().Type()
	// 	} else if entity.(reflect.Value).Kind() == reflect.Struct {
	// 		s = entity.(reflect.Value).Type()
	// 	} else {
	// 		s = entity.(reflect.Value).Type()
	// 	}
	// } else if typeOf.Kind() == reflect.Struct {
	// 	s = typeOf
	// } else {
	// 	s = entity.(reflect.Value).Type() //通过反射获取type定义
	// }

	// sDbName := dbinfo.GetDbName(entity)
	// sTableName := dbinfo.SimpleTableName(entity)
	//sMainTableKeyName := dbinfo.EntityKeyName(entity)

	if (nil != findByPageParam.Gcondition) && (len(findByPageParam.Gcondition.(map[string]interface{})) > 0) {
		condition := findByPageParam.Gcondition.(map[string]interface{})
		for key, val := range condition {
			if val == nil {
				continue
			}

			keyFieldName := key
			// if mu.isLowerStart(keyFieldName) {
			// 	keyFieldName = "G" + key
			// }

			//_, ok := s.FieldByName(keyFieldName) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
			if dbinfo.HasColumnName(entity, keyFieldName) {
				conditionMap[key] = val //明确值的字符串/日期/数字等都直接加入查询条件
				params[key] = val
				continue
			}

			if strings.HasSuffix(key, "St") { //以St结尾
				temp := key[0 : len(key)-2] //去掉结尾
				if dbinfo.HasColumnName(entity, temp) {
					conditionRangeStMap[temp] = val //明确值的字符串/日期/数字等都直接加入查询条件
					params[key] = val
				}

				// keyFieldName := temp
				// if mu.isLowerStart(keyFieldName) {
				// 	keyFieldName = "G" + temp
				// }

				// _, ok := s.FieldByName(keyFieldName) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
				// if ok {
				// 	conditionRangeStMap[temp] = val //明确值的字符串/日期/数字等都直接加入查询条件
				// 	params[key] = val
				// }

				continue
			}

			if strings.HasSuffix(key, "Ed") { //以Ed结尾
				temp := key[0 : len(key)-2] //去掉结尾
				if dbinfo.HasColumnName(entity, temp) {
					conditionRangeStMap[temp] = val //明确值的字符串/日期/数字等都直接加入查询条件
					params[key] = val
				}

				// keyFieldName := temp
				// if mu.isLowerStart(keyFieldName) {
				// 	keyFieldName = "G" + temp
				// }

				// _, ok := s.FieldByName(keyFieldName) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
				// if ok {
				// 	conditionRangeEdMap[temp] = val //明确值的字符串/日期/数字等都直接加入查询条件
				// 	params[key] = val
				// }
				continue
			}

			valType := reflect.TypeOf(val)
			if (strings.HasSuffix(key, "Array")) && (strings.HasPrefix(valType.String(), "[]")) { //以Array结尾,并且属于数组类型
				temp := key[0 : len(key)-len("Array")] //去掉结尾
				if !dbinfo.HasColumnName(entity, temp) {
					continue //字段名不存在
				}

				// keyFieldName := temp
				// if mu.isLowerStart(keyFieldName) {
				// 	keyFieldName = "G" + temp
				// }

				// _, ok := s.FieldByName(keyFieldName) //直接以字段名作为条件的(即不管是否以St或Ed结尾,都不属于范围条件)
				// if !ok {
				// 	continue //字段名不存在
				// }

				var sb strings.Builder
				sb.WriteString("(@@@@_@@@@")

				valArray := val.([]interface{})
				if strings.Contains("/int/int64/long/decimal/float64/", valType.String()) {
					for _, v := range valArray {
						sb.WriteString(",")
						sb.WriteString(fmt.Sprintf("%v", v))
					}
				} else {
					for _, v := range valArray {
						sb.WriteString(",'")
						sb.WriteString(fmt.Sprintf("%v", v))
						sb.WriteString("'")
					}
				}

				sb.WriteString(")")
				conditionArrayMap[temp] = strings.Replace(sb.String(), "@@@@_@@@@,", "", 1)

				continue
			}
		}
	}

	if sLikeStr != "" {
		var dLikeDateSt time.Time
		var dLikeDateEd time.Time

		if sLikeDateSt != "" {
			dLikeDateSt = timeutil.ToDate(sLikeDateSt)
		} else {
			dLikeDateSt = timeutil.AddDay(time.Now(), -7)
		}

		if sLikeDateEd != "" {
			dLikeDateEd = timeutil.ToDate(sLikeDateEd)
		} else {
			dLikeDateEd = time.Now()
		}

		params["dLikeDateSt"] = dLikeDateSt
		params["dLikeDateEd"] = dLikeDateEd
	}

	dataInfoList := dbinfo.AllDataInfo(entity)
	for _, dataInfo := range dataInfoList {
		if findByPageParam.GsLikeStr != "" {
			if !strings.Contains("/id/iId/uId/sId/sCreator/dCreateDate/sModifieder/dModifiedDate/iState/iSetp/iIndex/iVersion/", dataInfo.GsName) &&
				((dataInfo.GsDbFileType == "varchar") || (dataInfo.GsDbFileType == "char")) {
				conditionLikeMap = append(conditionLikeMap, dataInfo.GsTableName+"."+dataInfo.GsName)
			}
		}

		if findByPageParam.GsHideBigText && dataInfo.GbBigTxt { //如果开启了过滤大文本字段,则跳过
			continue
		}

		if findByPageParam.GsHideFields != "" { //如果是过滤字段则跳过
			if strings.Contains(findByPageParam.GsHideFields, ";"+dataInfo.GsName+";") {
				continue
			}
		}

		f, d := dao.GetFindByPageSelectSqlByField(dataInfo, entity.OwnerTable(), dataInfo.GsName, oTherJoin)
		if f != "" {
			appendFieldSql.WriteString(f)
		}

		if d != "" {
			dictionarySql.WriteString(d)
		}
	}

	var defaultOrderSql strings.Builder
	defaultOrderSql.WriteString(" ORDER BY @@@@_@@@@")

	if dbinfo.EntityHasIndex(entity) {
		defaultOrderSql.WriteString(",")
		defaultOrderSql.WriteString("${sTableName}.")
		defaultOrderSql.WriteString(dbinfo.TableIndexName)
	}

	if dbinfo.EntityHasModifiedDate(entity) {
		defaultOrderSql.WriteString(",")
		defaultOrderSql.WriteString("${sTableName}.")
		defaultOrderSql.WriteString(dbinfo.TableModifiedDateName)
		defaultOrderSql.WriteString(" DESC")
	}

	var vFindByPageWhere strings.Builder
	if onlyCreator && (dbinfo.EntityHasCreator(entity)) {
		currentLoginUserId := currentUser
		if !strings.Contains("/00000000/00000001/", currentLoginUserId) {
			vFindByPageWhere.WriteString("AND ${sTableName}.")
			vFindByPageWhere.WriteString(dbinfo.TableCreatorName)
			vFindByPageWhere.WriteString(" = '")
			vFindByPageWhere.WriteString(currentLoginUserId)
			vFindByPageWhere.WriteString("'")
		}
	}

	if len(conditionMap) > 0 {
		for key, val := range conditionMap {
			if strings.Contains(fmt.Sprintf("%v", val), "%") {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" LIKE @")
				vFindByPageWhere.WriteString(key)
			} else {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" = @")
				vFindByPageWhere.WriteString(key)
			}

			params[key] = val
		}
	}

	if len(conditionRangeStMap) > 0 {
		for key, val := range conditionRangeStMap {
			if fmt.Sprintf("%v", val) != "" {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" >= @")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString("St")
			}
		}
	}

	if len(conditionRangeEdMap) > 0 {
		for key, val := range conditionRangeEdMap {
			if fmt.Sprintf("%v", val) != "" {
				vFindByPageWhere.WriteString(" AND ${sTableName}.")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString(" <= @")
				vFindByPageWhere.WriteString(key)
				vFindByPageWhere.WriteString("Ed")
			}
		}
	}

	if len(conditionArrayMap) > 0 {
		for key, val := range conditionArrayMap {
			if fmt.Sprintf("%v", val) == "" {
				continue
			}

			vFindByPageWhere.WriteString(" AND ${sTableName}.")
			vFindByPageWhere.WriteString(key)
			vFindByPageWhere.WriteString(" IN (")
			vFindByPageWhere.WriteString(val)
			vFindByPageWhere.WriteString(")")
		}
	}

	if (sLikeStr != "") && (len(conditionLikeMap) > 0) {
		if dbinfo.EntityHasModifiedDate(entity) {
			vFindByPageWhere.WriteString(" AND ${sTableName}.")
			vFindByPageWhere.WriteString(dbinfo.TableModifiedDateName)
			vFindByPageWhere.WriteString(" >= @dLikeDateSt")
			vFindByPageWhere.WriteString(" AND ${sTableName}.")
			vFindByPageWhere.WriteString(dbinfo.TableModifiedDateName)
			vFindByPageWhere.WriteString(" <= @dLikeDateEd")
		}

		vFindByPageWhere.WriteString(" AND (@@@@_@@@@")

		for _, key := range conditionLikeMap {
			vFindByPageWhere.WriteString(" OR (")
			vFindByPageWhere.WriteString(key)
			vFindByPageWhere.WriteString(" LIKE CONCAT('%', @sLikeStr, '%'))")
		}

		vFindByPageWhere.WriteString(")")

		params["sLikeStr"] = sLikeStr
	}

	if dbinfo.EntityHasDelSign(entity) { //存在逻辑删除字段
		vFindByPageWhere.WriteString(" AND ")
		vFindByPageWhere.WriteString(entity.TableName())
		vFindByPageWhere.WriteString(dbinfo.TableDelSignName)
		vFindByPageWhere.WriteString(" != 1")
	}

	var findByPageCountSql strings.Builder
	findByPageCountSql.WriteString("SELECT COUNT(1) AS iCount FROM ")
	findByPageCountSql.WriteString(entity.TableName())

	if vFindByPageWhere.Len() != 0 {
		findByPageCountSql.WriteString(" WHERE ")
		findByPageCountSql.WriteString(vFindByPageWhere.String())
	}

	result0 := strings.Replace(findByPageCountSql.String(), "${sTableName}", entity.OwnerTable(), -1)
	result0 = strings.Replace(result0, "(@@@@_@@@@)", "", -1)
	result0 = strings.Replace(result0, "@@@@_@@@@ OR ", "", -1)
	result0 = strings.Replace(result0, " AND AND ", " AND ", -1)
	result0 = strings.Replace(result0, " WHERE    AND ", " WHERE ", -1)
	result0 = strings.Replace(result0, " WHERE   AND ", " WHERE ", -1)
	result0 = strings.Replace(result0, " WHERE  AND ", " WHERE ", -1)
	result0 = strings.Replace(result0, " WHERE AND ", " WHERE ", -1)

	var findByPageSql strings.Builder
	findByPageSql.WriteString("SELECT ")
	findByPageSql.WriteString(appendFieldSql.String())
	findByPageSql.WriteString(" ${sTableName}.* ")
	findByPageSql.WriteString(" FROM ${sDbTableName} AS ${sTableName} ")

	if dictionarySql.String() != "" {
		findByPageSql.WriteString(dictionarySql.String())
	}

	if vFindByPageWhere.Len() != 0 {
		findByPageSql.WriteString(" WHERE ")
		findByPageSql.WriteString(vFindByPageWhere.String())
	}

	if len(findByPageParam.Gorders) > 0 {
		findByPageSql.WriteString(" ORDER BY ")
		findByPageSql.WriteString("@@@@_@@@@")
		for _, val := range findByPageParam.Gorders {
			findByPageSql.WriteString(",")
			findByPageSql.WriteString(val.String())
		}
	} else {
		if !strings.Contains(defaultOrderSql.String(), " ORDER BY ") {
			findByPageSql.WriteString(" ORDER BY ")
		}

		findByPageSql.WriteString(defaultOrderSql.String())
	}

	if findByPageParam.Gpage.GiSize < 1 {
		findByPageParam.Gpage.GiSize = 10
	}

	if findByPageParam.Gpage.GiCurrent < 1 {
		findByPageParam.Gpage.GiCurrent = 1
	}

	findByPageSql.WriteString(" LIMIT ")
	findByPageSql.WriteString(strconv.Itoa((findByPageParam.Gpage.GiCurrent - 1) * findByPageParam.Gpage.GiSize))
	findByPageSql.WriteString(" , ")
	findByPageSql.WriteString(strconv.Itoa(findByPageParam.Gpage.GiSize))

	result1 := findByPageSql.String()

	result1 = strings.Replace(result1, "${sDbTableName}", entity.TableName(), -1)
	result1 = strings.Replace(result1, "${sTableName}", entity.OwnerTable(), -1)
	result1 = strings.Replace(result1, "@@@@_@@@@ OR ", "", -1)
	result1 = strings.Replace(result1, "@@@@_@@@@, ", "", -1)
	result1 = strings.Replace(result1, "ORDER BY @@@@_@@@@,", "ORDER BY ", -1)
	result1 = strings.Replace(result1, " ORDER BY @@@@_@@@@ LIMIT ", " LIMIT ", -1)
	result1 = strings.Replace(result1, " WHERE  AND ", " WHERE ", -1)
	result1 = strings.Replace(result1, " WHERE AND ", " WHERE ", -1)

	return result0, result1, params
}

// 取分页查询的字段信息
func (DaoBaseFunc) GetFindByPageSelectSqlByField(dataInfo *dbinfo.DataInfo, sTableName, sFieldName string, oTherJoin map[string]string) (string, string) {
	var appendFieldSql strings.Builder
	var dictionarySql strings.Builder

	//--发现关联表--//
	if (sTableName != dataInfo.GsTableName) && (dataInfo.GsRelName != "") && (dataInfo.GsRelMainName != "") {
		title := strings.TrimSpace(dataInfo.GsRelTitle)
		if title == "" {
			title = sFieldName
		}

		appendFieldSql.WriteString(" ")
		appendFieldSql.WriteString(dataInfo.GsTableName)
		appendFieldSql.WriteString("_")
		appendFieldSql.WriteString(dataInfo.GsRelName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dataInfo.GsName)
		appendFieldSql.WriteString(" AS ")
		appendFieldSql.WriteString(title)
		appendFieldSql.WriteString(",")

		var leftJoinName strings.Builder
		leftJoinName.WriteString(dataInfo.GsTableName)
		leftJoinName.WriteString("_")
		leftJoinName.WriteString(dataInfo.GsRelName)

		_, ok := oTherJoin[leftJoinName.String()]
		if ok { //已经存在
			return appendFieldSql.String(), dictionarySql.String()
		}

		var leftJoin strings.Builder
		leftJoin.WriteString(" LEFT JOIN ")
		leftJoin.WriteString(gorm.GetDbName(dataInfo.GsDbName))
		leftJoin.WriteString(dataInfo.GsTableName)
		leftJoin.WriteString(" AS ")
		leftJoin.WriteString(leftJoinName.String())
		leftJoin.WriteString(" ON (")
		leftJoin.WriteString(dataInfo.GsTableName)
		leftJoin.WriteString("_")
		leftJoin.WriteString(dataInfo.GsRelName)
		leftJoin.WriteString(".")
		leftJoin.WriteString(dataInfo.GsRelName)
		leftJoin.WriteString(" = ")
		leftJoin.WriteString(gorm.GetDbName(dataInfo.GsDbName))
		leftJoin.WriteString(sTableName)
		leftJoin.WriteString(".")
		leftJoin.WriteString(dataInfo.GsRelMainName)
		leftJoin.WriteString(") ")

		oTherJoin[leftJoinName.String()] = leftJoin.String() //防止重复累加相同的关联

		dictionarySql.WriteString(leftJoin.String())

		return appendFieldSql.String(), dictionarySql.String()
	}

	//--检查备注中的通用关联--//
	sComment := stringutil.SubBetween(dataInfo.GsComment, "(", ")", true)
	if sComment == "" {
		return appendFieldSql.String(), dictionarySql.String()
	}

	if strings.HasPrefix(sComment, "枚举") { //枚举类型
		sComment = sComment[len("枚举")+1:]
		comment := strings.Split(sComment, ";")
		if len(comment) < 1 {
			return appendFieldSql.String(), dictionarySql.String()
		}

		appendFieldSql.WriteString(" CASE ")
		appendFieldSql.WriteString(dataInfo.GsTableName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dataInfo.GsName)

		for _, val := range comment {
			array := strings.Split(val, ":")
			if len(array) < 1 {
				return appendFieldSql.String(), dictionarySql.String()
			}

			if len(array) < 2 {
				array = append(array, "缺失")
			}

			appendFieldSql.WriteString(" WHEN ")
			appendFieldSql.WriteString(array[0])
			appendFieldSql.WriteString(" THEN '")
			appendFieldSql.WriteString(array[1])
			appendFieldSql.WriteString("' ")
		}

		appendFieldSql.WriteString(" ELSE '未知' END AS s")
		appendFieldSql.WriteString(dataInfo.GsName[1:])
		appendFieldSql.WriteString("Text,")

		return appendFieldSql.String(), dictionarySql.String()
	}

	if strings.HasPrefix(sComment, "布尔值,") { //布尔值
		sComment = sComment[len("布尔值,"):]
		comment := strings.Split(sComment, ";")
		if len(comment) <= 0 {
			return appendFieldSql.String(), dictionarySql.String()
		}

		appendFieldSql.WriteString(" CASE ")
		appendFieldSql.WriteString(sTableName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dataInfo.GsName)

		for _, val := range comment {
			val = strings.TrimSpace(val)
			if val == "" {
				return appendFieldSql.String(), dictionarySql.String()
			}

			array := strings.Split(val, ":")
			if len(array) < 1 {
				return appendFieldSql.String(), dictionarySql.String()
			}

			if len(array) < 2 {
				array = append(array, "缺失")
			}

			appendFieldSql.WriteString(" WHEN ")
			appendFieldSql.WriteString(array[0])
			appendFieldSql.WriteString(" THEN '")
			appendFieldSql.WriteString(array[1])
			appendFieldSql.WriteString("' ")
		}

		appendFieldSql.WriteString(" ELSE '否' END AS s")
		appendFieldSql.WriteString(dataInfo.GsName[1:])
		appendFieldSql.WriteString("Text,")

		return appendFieldSql.String(), dictionarySql.String()
	}

	if strings.HasPrefix(sComment, "字典") { //字典
		appendFieldSql.WriteString(" Dictionary_")
		appendFieldSql.WriteString(dataInfo.GsName)
		appendFieldSql.WriteString(".")
		appendFieldSql.WriteString(dbinfo.TableTreeNodeName)
		appendFieldSql.WriteString(" AS s")
		appendFieldSql.WriteString(dataInfo.GsName[1:])
		appendFieldSql.WriteString("Text,")

		dictionarySql.WriteString(" LEFT JOIN ")
		dictionarySql.WriteString(gorm.GetDbName(dbinfo.BaseSystemName))
		dictionarySql.WriteString(dbinfo.TableNameDictionary)
		dictionarySql.WriteString(" AS Dictionary_")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(" ON (Dictionary_")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(".")
		dictionarySql.WriteString(dbinfo.TableOnlyignName)
		dictionarySql.WriteString(" LIKE '")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString("%' AND Dictionary_")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(".")
		dictionarySql.WriteString(dbinfo.TableDictionaryValueName)
		dictionarySql.WriteString(" = CAST(")
		dictionarySql.WriteString(sTableName)
		dictionarySql.WriteString(".")
		dictionarySql.WriteString(dataInfo.GsName)
		dictionarySql.WriteString(" AS CHAR)) ")

		return appendFieldSql.String(), dictionarySql.String()
	}

	return appendFieldSql.String(), dictionarySql.String()
}

// 对gorm.First操作进行封装
func (DaoBaseFunc) First(entity dbinfo.Entity, conds ...interface{}) (dbinfo.Entity, error) {
	dbResult := gorm.GetDB().Table(entity.TableName()).First(entity, conds...)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return nil, dbResult.Error
	}

	if dbResult.RowsAffected < 1 {
		return nil, errors.New("没有查询到数据")
	}

	return entity, nil
}

// 对gorm.Create操作进行封装
func (DaoBaseFunc) Create(entity dbinfo.Entity) (dbinfo.Entity, error) {
	dbResult := gorm.GetDB().Table(entity.TableName()).Create(entity)
	if dbResult.Error != nil {
		Log.Error("新增发生异常:", dbResult.Error)
		return nil, dbResult.Error
	}

	if dbResult.RowsAffected < 1 {
		return nil, errors.New("新增失败,影响数为0")
	}

	return entity, nil
}

// 对gorm.Save操作进行封装,
// 警告:Save是一个组合函数。 如果保存值不包含主键，它将执行 Create，否则它将执行 Update (包含所有字段)。
func (DaoBaseFunc) Save(entity dbinfo.Entity) (dbinfo.Entity, error) {
	dbResult := gorm.GetDB().Table(entity.TableName()).Save(entity)
	if dbResult.Error != nil {
		Log.Error("更新发生异常:", dbResult.Error)
		return nil, dbResult.Error
	}

	if dbResult.RowsAffected < 1 {
		return nil, errors.New("更新失败,影响数为0")
	}

	return entity, nil
}

// 对gorm.Delete操作进行封装
func (DaoBaseFunc) Delete(entity dbinfo.Entity, conds ...interface{}) (int, error) {
	dbResult := gorm.GetDB().Table(entity.TableName()).Delete(entity, conds...)
	if dbResult.Error != nil {
		Log.Error("删除发生异常:", dbResult.Error)
		return 1001, dbResult.Error
	}

	iCode := dbResult.RowsAffected
	if iCode < 1 {
		return 1002, errors.New("删除失败,影响数为0")
	}

	return int(iCode), nil
}
